Scala 自身类型(self-type) 解析
2018-02-14 07:08
267 查看
Scala 有一个自身类型(self-type) 的东西,由来已久,居然今天才发现。如果一个类或 trait 指明了 self-type 类型(包括类和特质),它的子类型或是对象也必须是相应的类型。它产生的效果与继承(或 mixin) 颇有几分相似。self-type 的语法是
trait Tweeter {
this: User => //这个表示 Tweeter 本身也必须是一个 User,它的子类型必须想办法符合这一要求
def tweet(tweetText: String) = {
println(s"$name: $tweetText")
}
}
class VerifiedTweeter(val username: String)
extends User(username) with Tweeter { //Tweeter 要求这个类必须是一个 User, 所以需要继承自 User 类
}
val v = new VerifiedTweeter("Yanbin")
v.tweet("Hello")上面
this 的别名: 某一类型(class 或 trait), 直接看一个例子:class User(val name: String)
trait Tweeter {
this: User => //这个表示 Tweeter 本身也必须是一个 User,它的子类型必须想办法符合这一要求
def tweet(tweetText: String) = {
println(s"$name: $tweetText")
}
}
class VerifiedTweeter(val username: String)
extends User(username) with Tweeter { //Tweeter 要求这个类必须是一个 User, 所以需要继承自 User 类
}
val v = new VerifiedTweeter("Yanbin")
v.tweet("Hello")上面
this: User =>中的
this只是一个别名,可以是
self或任何有效标识(如
abc: User),这里使用
this等于未指定别名,与原本的 this 重叠了。如果声明为非
this的话则可以这么用 阅读全文 >>
相关文章推荐
- 【Scala类型系统】自身类型(self type)引用
- Scala之自身类型(Self Type)与蛋糕模式(Cake Pattern)
- 【Scala类型系统】自身类型(self type)引用
- 自身类型(self type)
- ArcIMS 解析字段类型为Date(type="91")日期时间
- Scala类型 9:自身类型 & this别名
- scala进阶14-自身类型self type
- python数据类型判断type与isinstance的区别实例解析
- scala类型系统:3) 单例类型与this.type
- Scala 类型: Type vs. Class(类型与类)
- Scala类型 8:type 关键字
- Scala类型 10 :交集类型(intersection type)与联合类型(union type)
- Type、Array、List、Tuple模式匹配实战解析之Scala学习笔记-18
- Scala入门之高级类型:this.type
- Scala类型约束代码实战及其在Spark中的应用源码解析之Scala学习笔记-39
- Scala新手指南中文版 -第七篇 The Either type(Either类型)
- Scala新手指南中文版 -第五篇 The Option Type(Option类型)
- scala-46: ClassTag 、Manifest、ClassManifest、TypeTag代码实战及其在Spark中的应用源码解析
- Ibatis的类型处理器TypeHandler解析
- Scala深入浅出进阶经典 第43讲:Scala中类型变量Bounds代码实战及其在Spark中的应用源码解析