Scala 类型系统深入剖析:抽象类型、自类型注解与结构类型
1. 避免使用视图边界
在编写代码时,建议避免使用视图边界,因为它们未来可能会被弃用。
2. 理解抽象类型
2.1 抽象类型的基本概念
参数化类型在静态类型的面向对象语言中很常见,而 Scala 还支持抽象类型,这种类型在一些函数式语言中较为常见。以下是一个使用抽象类型的示例:
// src/main/scala/progscala2/typesystem/abstracttypes/abstract-types-ex.sc
trait exampleTrait {
type t1 // t1 is unconstrained
type t2 >: t3 <: t1 // t2 must be a supertype of t3 and a subtype of t1
type t3 <: t1 // t3 must be a subtype of t1
type t4 <: Seq[t1] // t4 must be a subtype of Seq of t1
// type t5 = +AnyRef // ERROR: Can't use variance annotations
val v1: t1 // Can't initialize until t1 defined.
val v2: t2 // ditto...
val v3: t3
超级会员免费看
订阅专栏 解锁全文
32

被折叠的 条评论
为什么被折叠?



