- Basics
val greeting: String = null
val xma, ymax = 100 // both are set
String -> StringOps //intersect, sorted...
Int -> RichInt // 1.to(10)
primitive -> Rich*
BigInt & BigDecimal // * can be applied
apply method on both class and companion object
- Control Structures & Functions
val s = if (x>0) 1 else -1
if (x > 0) 1 else () // () is type of Unit
x = y = 1 // x is Unit
while & for // no break inside loop, use boolean, nested function or Breaks object instead
for(i <- 1 to n) r = r*i // no val or var i
import scala.util.control.Breaks._
breakable {
for (...) {
if (...) break; // Exits the breakable block
...
}
}
val n = ...
for (n <- 1 to 10) {
// Here n refers to the loop variable
}
variable shadowing rule, two n variables above
advanced for loops
for (i <- 1 to 3; j <- 1 to 3 if i != j) print(f"${10 * i + j}%3d")
for (i <- 1 to 3; from = 4 - i; j <- from to 3) print(f"${10 * i + j}%3d") // from is a varaible
for (i <- 1 to 10) yield i % 3 // generate a collection
============functions============
def abs(x: Double) = if(x>0) x else -x
def fac(n: Int):Int = if(n<=0) 1 else n*fac(n-1) // return type is needed for recursive call
def decorate(str: String, left: String = "[", right: String = "]") = left + str + right //named and default parameter.
//decorate(left = "<<<", str = "Hello", right = ">>>"), order doesn't matter
def sum(args: Int*) = { //sum(1,2,3)
var result = 0
for(i <- args) result += i
result
}
for existing sequence, seq, use sum(seq: _*). e.g., sum(1 to 5: _*)
MessageFormat.format("The answer to {0} is {1}","everything", 42. asInstanceOf[AnyRef]) // primitive value in variable object parameters.val words = scala.io.Source.fromFile("/usr/share/dict/words").mkString
// Evaluated as soon as words is defined
lazy val words = scala.io.Source.fromFile("/usr/share/dict/words").mkString
// Evaluated the first time words is used, need to if it's initialized every time it's accessed.
def words = scala.io.Source.fromFile("/usr/share/dict/words").mkString
// Evaluated every time words is used
===============Exception================
if (x >= 0) { sqrt(x)} else throw new IllegalArgumentException("x should not be negative") //exception with type of Nothing. the type of this statement is Double.
try{ process..} catch {
case _: SomeException => ...
case ex: IOException => ...
}finally{...}
- Arrays
val s = Array("Hello", "World") // length is fixed
s.toBuffer
s(0)// Hello
val ab = ArrayBuffer[Int]() //length is variable
ab += 1; ab += (2,3,4); ab ++= Array(5,6); ab.trimEnd(4);//it's efficient to remove head or tail elements from array buffer. no elements shift.
ab.insert(2, 6); ab.remove(2); ab.remove(2, 3);
ab.toArray
sum, max, mkString, append, count ...
Array.ofDim[Int](3, 4) //multiple-dimension array
===============scala java converters=================
asJava, asScala
* - `scala.collection.Iterable` <=> `java.lang.Iterable`
* - `scala.collection.Iterator` <=> `java.util.Iterator`
* - `scala.collection.mutable.Buffer` <=> `java.util.List`
* - `scala.collection.mutable.Set` <=> `java.util.Set`
* - `scala.collection.mutable.Map` <=> `java.util.Map`
* - `scala.collection.mutable.concurrent.Map` <=> `java.util.concurrent.ConcurrentMap`
asJavaCollection, asJavaEnumeration, asJavaDictionary
* - `scala.collection.Iterable` <=> `java.util.Collection`
* - `scala.collection.Iterator` <=> `java.util.Enumeration`
* - `scala.collection.mutable.Map` <=> `java.util.Dictionary`
one way conversion, asJava
* - `scala.collection.Seq` => `java.util.List`
* - `scala.collection.mutable.Seq` => `java.util.List`
* - `scala.collection.Set` => `java.util.Set`
* - `scala.collection.Map` => `java.util.Map`
- Maps and Tuples
val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8) //"Alice" -> 10 creates tuple
scores("Bob") //throw exception if not exists
scores.getOrElse("calf", 0)//return Option
val scores1 = scores.withDefaultValue(0); scores1.get("xxx")//return 0
val scores2 = scores.withDefault(_.length); scores2.get("yyyy")//return 4
val scoreMore = scores + ("calf" -> 30) // add more key/value on immutable map to create a new map
val scoreLess = scores - "Alice" //remove to create a new map
val scores = mutable.Map[String, Int]()
scores("Bob") = 11
scores += ("Alice" -> 3, "xx" -> 4)
scores -= ..
============tuple==========
val symbols = Array("<", "-", ">")
val counts = Array(2, 10, 2)
val pairs = symbols.zip(counts)