结构类型
结构类型(Struture Type)通过利用反射机制为静态语言添加动态特性,从面使得参数类型不受限于某个已命名的的类型.直接看代码,更理解理解
package com.dt.scala.moguyun
/**
* Created by hlf on 2016/8/9.
* 结构体类型其实可以看作是一个类,在函数调用时,
* 直接通过new操作来创建一个结构体类型对象,当然它是匿名的。
* 因此,方法也可以传入一个实现了方法的类或单例对象
*/
object StrutureType extends App {
/**
* 这里有个move方法,参数是结构类型,要求传入的是run方法
*/
def move(m: {def run(): Unit}) = {
println("when is my turn")
//使用时把它当作类来看,直接点出这个匿名类的run方法。
m.run()
}
//因为可以看作是类,所以直接new出来也可以
move(new {
def run() = println("i will never come here again!")
})
//直接传入类,只要它符合结构类型
move(new Move())
//直接传入单例,只要它符合结构类型
move(Move)
}
class Move {
def run() = println("I'm running quickly!")
}
object Move {
def run() = println("I'm running slowly!")
}
运行结果
when is my turn
i will never come here again!
when is my turn
I'm running quickly!
when is my turn
I'm running slowly!
结构体类型还可以用type关键字进行声明,这里就不说了,觉得用得最多的还是传入类或单例。