Copyright © Cay S. Horstmann 2015
Application Programmer | Library Designer | Overall Scala Level |
---|---|---|
Beginning A1 | Beginning | |
Intermediate A2 | Junior L1 | Intermediate |
Expert A3 | Senior L2 | Advanced |
Expert L3 | Expert |
Live demo of worksheets
Int
, Double
, Boolean
, String
.+ - * / %
like in Java.val answer = 8 * 5 + 2 // answer is an Int
var greeting: String = null
val
: immutable, var
: mutable.
val
whenever you can.Int
, Double
, Byte
, Char
, Short
, Long
, Float
, Boolean
.1.to(10) // Apply to method to 1, returns Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
to
method is actually defined in RichInt
.java.lang.String
is available in Scala.StringOps
:
"Hello".intersect("World") // Yields "lo"
val x: BigInt = 1234567890 x * x * x // Yields 1881676371789154860897069000
1 to 10 // Same as 1.to(10) 1 + 10 // Same as 1.+(10)
++
, --
operators do not exist in Scala.
+=
instead: counter += 1
.import scala.math._ sqrt(2) // A function BigInt.probablePrime(100, scala.util.Random) // A method
()
:
"Hello".distinctRule of thumb:
()
only required for mutators(arg)
for methods that are similar to function calls:
"Hello"(4) // Yields 'o'
apply
method:
"Hello".apply(4) // same as "Hello"(4)
scala.math
), RichXxx
, StringOps
.def count(p: (Char) => Boolean): Int
Range
, Seq[Char]
mean what you think they do.def scan[B >: Char, That](z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[String, B, That]): That
Lesson1
. Sheet1
. }
. Type 6 * 7
and then save (Ctrl+S/⌘+S). What do you get?val a = 6 * 7
and save. What do you get?a
. What do you get? a = 43
. What do you get? Why?val b;
(This time with a semicolon.) What do you get? Why?val b: BigInt = 6 * 7
. What do you get?b.pow(1000)
. What do you get?import scala.math._
just above the }
.sqrt(10)What do you get?
1.to(10)
. What do you get?1.to(10).map(sqrt(_))
. What do you get? 6.*(7)
. What do you get? Why?Int
, then click on the large C icon. Watch it turn into an O. java.lang.Integer.MAX_VALUE
?StringOps
. distinct
. "Mississippi".distinct
to be?permutations
. "Rhine".permutations
to be?.toArray
. Now what do you get?"ABC".sum
? Why? (Hint: Try 'A'.toInt
and "ABC".sum.toInt
)