一、Abstract Types 概念
所谓Abstract Types 成员, 是指trait ,class , Abstract class 使用 type 关键字 来定义类型,让实现类来指定具体的类型,
如:
trait Reader{
type In <:java.io.Serializable //这里使用type定义的In类型,但并没有指明In是什么类型
type Contents //这里使用type定义的Contents类型,但并没有指明Contents是什么类型
def read(in:In):Contents
}
class FileReader extends Reader{
type In = String //在实现类中,使用type 来指明 In 的具体类型
type Contents = BufferedSource //在实现类中,使用type 来指明 Contents 的具体类型
override def read(name:In) = Source.fromFile(name)
}
大家发现,通过type 的定义的In和 Contents 类型 可以作为作为参数类型在 方法中使用。
或许大家会想,实现这个功能,也可以使用参数类型,如
trait Reader[In,Contents ]{
def read(in:In):Contents
}
class FileReader[String,BufferedSource] extends Reader{
override def read(name:In) = Source.fromFile(name)
}
确实没有什么问题。
二、Abstract Types 与 参数类型的取舍
- 建议尽可能使用Abstract Types
- 类型参数有约束,个数多的情况,建议使用 Abstract Types
参考资料
1. 土豆网 第58讲:Scala中Abstract Types实战详解
2. 百度云盘 第58讲:Scala中Abstract Types实战详解
3. http://www.artima.com/weblogs/viewpost.jsp?thread=270195
另外
欢迎广大Spark爱好者学习交流.也欢迎广大学习爱好者加入
DT大数据梦工厂交流群:462923555
DT大数据微信公众账号:DT_Spark