Tuesday, October 25, 2016

Programming in Scala Note Chapter 1/2/3

Chapter 1/2/3
1.

def factorial(x: BigInt): BigInt =
    if (x == 0) 1 else x * factorial(x - 1)
2.
A val is similar to a final variable in Java. Once
initialized, a val can never be reassigned. A var, by contrast, is similar to a non-final variable in Java. 
3.
Sometimes the Scala compiler will require you to specify the result type of a function. If the function
is recursive,[7] for example, you must explicitly specify the function's result type.
If a function consists of just one statement, you can optionally leave off the curly braces.
scala> def max(x: Int, y: Int) = if (x > y) x else y
4.
scala> def greet() = println("Hello, world!")
greet: ()Unit
A result type of Unit indicates the function returns no interesting value.
5.
Note that Java's + +i and i++ don't work in Scala. To increment in Scala, you need to say either i = i + 1 or i += 1.
6.
args.foreach(arg => println(arg))
or   
args.foreach((arg: String) => println(arg))
or
args.foreach(println)
or
for(arg <- args) println(arg)
7.
If the method name ends in a colon, the
method is invoked on the right operand.
8.
The time it takes to append to a list grows linearly with the size of the
list, whereas prepending with :: takes constant time. If you want to build a list efficiently by appending
elements, you can prepend them and when you're done call reverse. Or you can use a ListBuffer, a
mutable list that does offer an append operation, and when you're done call toList.
9.
Once you have a tuple instantiated, you can access its elements individually with a dot,
underscore, and the one-based index of the element.
val pair = (99, "Luftballons")
println(pair._1)
10.
This -> method, which you can invoke on any
object in a Scala program, returns a two-element tuple containing the key and value.
import scala.collection.mutable
val treasureMap = mutable.Map[Int, String]()
treasureMap += (1 -> "Go to island.")
11.
if code contains any vars, it is probably in an imperative style. If the code contains no vars at all—i.e., it
contains only vals—it is probably in a functional style.

No comments:

Post a Comment