在看scalatra源代码时,看到它在一段代码中,使用了type关键字,如下:
type Attributes = {def getAttribute(name: String): AnyRef def getAttributeNames(): java.util.Enumeration[_] def setAttribute(name: String, <span class="kwrd">value</span>: AnyRef): Unit def removeAttribute(name: String): Unit
}```
这个type是干什么用的呢?
@爱国者给了一段代码,解答了这个问题,如下:
type A = {def func : Int
}
val a: A = new{
def func = 2;
}class B{
def func = 20 def print = println(<span class="str">"hello world"</span>)
}
val b = new B
var bb: A = b<p>看起来,type定义的,就像是一个接口。然后神奇的地方在于,class B,与type A看起来并没有任何关系,但是它却能赋给A!仅仅是因为A定义的函数,B也有 这和动态语言中的duck type非常相似,即只要你的函数签名与我期望的一样,我就可以把你当作另一个类型来使用。不同的是,scala还让它拥有了静态编译的优点。 真没想到,原以为动态语言中才能有的特性,在scala中也可以实现。