结构类型:指一组关于抽象的方法、字段或类型的规格说明,这些抽象方法、字段、类型是我们传进参数或者说要使用相关的对象必须具备的。
在javascript或者Ruby中,只要看起来、走起来、叫起来像鸭子,我们就认为它是鸭子。
在javascript或者Ruby中,只要看起来、走起来、叫起来像鸭子,我们就认为它是鸭子。
在构建复杂表达式时,不想从类/接口去限制它,这种方式含有动态语言的灵活性和简洁性
class Structural{
def open() = println("A class instance Opened")
}
object Structural_Type_53 {
//于object而言,是全局的方法
def init(res : {def open() : Unit}){ //init方法要求传进的对象中有一个方法open(),只要传进的对象有open方法,这个对象就可以传进来。
//我们并不关心传进的对象的类型,我们对传进来的对象只有一个要求:就是它必须具备open()
res.open
}
def main(args: Array[String]): Unit = {
init(new {def open() = println("opened")}) //new一个匿名对象
type x = {def open() : Unit} //type关键字:把等号后面的内容命名为x
def init(res : x) = res.open //局部的本地方法(main方法里又定义方法)
init(new {def open() = println("opened again")})
object A {def open(){println("A single object opened")}}
init(A) //传入单例对象object A
val structural = new Structural
init(structural) //传入类对象的实例
}
}
输出:
opened
opened again
A single object opened
A class instance Opened
参考资料来源于大数据梦工厂 深入浅出scala 第53讲 由王家林老师讲解