Scala for the Impatient -- 2nd Edition


Chapter 1. The Basics


In [1]:
println(s"""Details of exec env ==>
    |    ${util.Properties.versionMsg}
    |    ${util.Properties.javaVmName} ${util.Properties.javaVersion} ${util.Properties.javaVmVersion}"""
.stripMargin)


Details of exec env ==>
    Scala library version 2.11.8 -- Copyright 2002-2016, LAMP/EPFL
    Java HotSpot(TM) 64-Bit Server VM 1.8.0_131 25.131-b11

Qn#2. In the Scala REPL, compute the square root of 3, and then square that value. By how much does the result differ from 3? (Hint: The res variables are your friend.)


In [2]:
import math._

3 - pow(sqrt(3), 2)


Out[2]:
4.440892098500626E-16

Qn#4. Scala lets you multiply a string with a number—try out "crazy" * 3 in the REPL. What does this operation do? Where can you find it in Scaladoc?


In [3]:
"crazy" * 3


Out[3]:
crazycrazycrazy

Qn#5. What does 10 max 2 mean? In which class is the max method defined?


In [4]:
10 max 2


Out[4]:
10

Qn#6. Using BigInt, compute 2<sup>1024</sup>.


In [5]:
BigInt(2).pow(1024)


Out[5]:
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216

Qn#7. What do you need to import so that you can get a random prime as probablePrime(100, Random), without any qualifiers before probablePrime and Random?


In [6]:
import util._
import BigInt._

probablePrime(100, Random)


Out[6]:
746399841880343649071464112899

Qn#9. How do you get the first character of a string in Scala? The last character?


In [7]:
val title = "Scala for the Impatient"

// Java-style
println("Java-style:-")
println(s"\tFirst character: ${title(0)}")
println(s"\tLast character: ${title(title.length - 1)}")

// Scala-style
println("\nScala-style:-")
println(s"\tFirst character with head method: ${title.head}")
println(s"\tFirst character with take method: ${title.take(1)}")
println(s"\tFirst character with dropRight method: ${title.dropRight(title.length - 1)}\n")

println(s"\tLast character with tail method: ${title.tail(title.length-2)}")
println(s"\tLast character with drop method: ${title.drop(title.length - 1)}")
println(s"\tLast character with takeRight method: ${title.takeRight(1)}")


Java-style:-
	First character: S
	Last character: t

Scala-style:-
	First character with head method: S
	First character with take method: S
	First character with dropRight method: S

	Last character with tail method: t
	Last character with drop method: t
	Last character with takeRight method: t