一、函数当做参数
def oncePerSecond(callback: () => Unit) {
val random = new Random
while(true) {
callback();
Thread sleep 10
println(random.nextInt(50))
}
}
二、惰性赋值
//惰性赋值:当使用lazy修饰一个val成员时,其赋值情况是在需要时才赋值的(by need)
// lazy val field = computation()
三、协变、逆变样例
def contravariant = {
val a:Consumer[Bird] = new Consumer[Bird](new Bird())
// val b:Consumer[Animal] = a // wrong
val a1:Consumer1[Bird] = new Consumer1[Bird](new Bird())
val b1:Consumer1[Animal] = a1 //协变 向上转型
println(b1)
val b2:Consumer1[Animal] = new Consumer1[Animal](new Animal())
// val a2:Consumer1[Bird] = b2 // wrong
val b3:Consumer2[Animal] = new Consumer2[Animal](new Animal())
val a3:Consumer2[Bird] = b3 //逆变 向上转型
}
四、for表达式中的模式
import scala.collection.JavaConversions.propertiesAsScalaMap
for ((k,v)<- System.getProperties) println(k+"="+v)
五、case class copy and 带名参数
val p1 = Person("id1","name1",11)
val p2 = p1.copy()
println(s"p1=$p1")
println(s"p2=$p2")
val p3 = p1.copy(name="name2")
println(s"p3=$p3")
六、偏函数
val foo : Option[String] => String = {
case Some(e) => e
case None => "???"
}
七、传值调用:先计算参数表达式的值,传名调用:将未计算的参数表达式直接应用到函数内部
object Add {
def addByName(a: Int, b: => Int) = a + b
def addByValue(a: Int, b: Int) = a + b
}
addByName(2, 2 + 2)
->2 + (2 + 2)
->2 + 4
->6
addByValue(2, 2 + 2)
->addByValue(2, 4)
->2 + 4
->6
八、CanBuildFrom
http://blog.bruchez.name/2012/08/getting-to-know-canbuildfrom-without-phd.html
def combineValues[U, T[_]](pairs : Seq[(U, U)])
(implicit cbf : CanBuildFrom[T[U], U, T[U]]): Seq[(U, T[U])] = {
val result = LinkedHashMap[U, Builder[U, T[U]]]()
for ((name, value) ← pairs)
result.getOrElseUpdate(name, cbf()) += value
result map { case (k, v) ⇒ k → v.result } toList
}
def combine_value = {
val seq = Seq[(String,String)](("n1","v1"),("n2","v2"),("n1","v3"))
println(combineValues[String,Set](seq))
}