Scala学习笔记 A3/L2篇 - 高级类型 Advanced Types

教材:快学Scala

chapter 18. 高级类型 Advanced Types

18.1 单例类型 Singleton Types

*what the fuck*
对于引用p,p.type是一个单例类型,值只能为p或者null
对于单例对象P,P.type是一个单例类型,值只能为P或者null

class MyPair[S, T](val first: S, val second: T)
val p = new MyPair(1, 2.0)
val pt: p.type = p // 值只能为p或者null
println(pt.first, pt.second) // (1,2.0) p和pt一模一样

object P { val first = 1; val second = 2 }
val Pt: P.type = P // 值只能为P或者null
println(P.first, P.second)   // (1,2.0)
println(Pt.first, Pt.second) // (1,2.0) P和Pt一模一样
object Title // 单例对象
object Desc // 单例对象

class Document {
    private var useNextArgAs: Any = null
    private var title: String = null
    private var desc: String = null
    def set[T](obj: T): this.type = { useNextArgAs = obj; this } // this.type 类型用于有继承关系的链式调用
    def to(arg: String) = useNextArgAs match { // useNextArgAs 匹配不同的单例类型
        case tt: Title.type => title = arg
        case dt: Desc.type => desc = arg
        case _ => arg
    }
    def p = println("title = " + title + "desc = " + desc)
}

val book = new Document
book set Title to "Scala for the impatient" // "fluent interfaces"
book set Desc to "a book full of joy when reading"
book p

18.2 类型投影 Type Projections

嵌套类

class Network {
    class Memeber {...}
    ...
}
val chatter = new Network
val myFace = new Network

每个Network实例的Member是不同的类,即chatter.Member和myface.Member是不同的类。
类型投影Network#Member 表示"任何Network的Member"

18.4 类型别名 Type Aliases

  • 类型别名 type Index = HashMap[String, (Int, Int)]
    类型别名必须被嵌套在类或对象中,不能出现在Scala文件的顶层。

18.5 结构类型 Structural Types

  • 描述一个变量必须有哪些抽象方法/字段/替他规格说明
    def appendLines(target: {def append(str: String): Any}, ...) {...}
    target可以为任何有append方法的实例,比定义一个Appendable特质要灵活,但是使用反射机制调用target.append,反射调用的开销要大得多(much more expensive)
  • 鸭子类型(duck typing):结构类型与js中的鸭子类型很类似,即:obj不需要一定是Duck类的实例,运行时只要obj.quack()在被调用那一刻检查到有quack方法就能调用成功。

18.6 复合类型 Compound Types

T1 with T2 with T3 也叫交集类型
trait ImageShape extends Shape with Serializable 的意思是
trait ImageShape extends (Shape with Serializable)

18.7 中置类型 Infix Types

带有两个类型参数的类型T1 A T2

18.8 存在类型 Existential Types

为了与Java的类型通配符兼容

  • 存在类型 类型表达式后面跟上forsome {...}
    Array[_ <: JComponent] 等价于 Array[T] forsome { type T <: JComponent }
    Array[_] 等价于 Array[T] forSome { type T }
    Map[_, _] 等价于 Map[T, U] forSome { type T; type U }

18.9 方法类型 method type

Scala编译器内部使用的类型,方法类型表示为(T1, ..., Tn)T 不带=>

def square(x: Int) = x * x // 方法,类型为(x: Int)Int
val triple = (x: Int) => 3 * x // 函数,类型为Int => Int = 

18.10 自身类型 Self Types

用于使trait可以要求混入它的类扩展自另一个实例
用法 this: 类型 =>
自身类型不会自动继承,在子类中需要重复自身类型的声明

你可能感兴趣的:(Scala学习笔记 A3/L2篇 - 高级类型 Advanced Types)