apply的用法,转自:http://my.oschina.net/scipio/blog/279735
package com.wandoujia.incognito /** * Created by XXXX on 16/2/1. */ class ApplyDemo { def apply() = "apply in class" def test{ println("test") } } /** * 伴生对象,相当于类的静态方法 */ object ApplyDemo { def stat{ println("static method") } def apply() = new ApplyDemo var count = 0 def incc = { count += 1 } } object Main extends App{ ApplyDemo.stat //类名后面加括号,相当于调用伴生对象的apply方法 val a = ApplyDemo() a.test //对象加括号相当于调用对象的apply方法 println(a()) val b = ApplyDemo.apply() b.test println(a.apply()) for(i <- 0 until 10){ ApplyDemo.incc } println(ApplyDemo.count) }
结果如下:
static method
test
apply in class
test
apply in class
apply通常被称作注入方法
unapply通常被称为提取方法,使用unapply来提取固定数量的对象,使用unapplySeq来提取一个序列
如:
object Student {
def unapply(str: String): Option[(String, String, String)] = {
val parts = str.split(",")
if (parts.length == 3) Some(parts(0), parts(1), parts(2)) else None
}
}
object Name {
def unapplySeq(input: String): Option[Seq[String] =
if (input == "") None else Some(input.trim.split("\\s+"))
}