Scala型別 6:複合型別 & with關鍵字
阿新 • • 發佈:2019-02-09
with 關鍵字:
class A extends B with C with D with E
解讀方式:
class A extends (B with C with D with E)
(B with C with D with E)首先是一個整體,再由 A 去繼承。
注:對於Java中的菱形繼承問題;Scala的解決策略是:
1. 繼承class混入trait:(extends SuperClass with subClass|subTrait with … ) 必須是一個繼承鏈(左->右)
2. 繼承無關的多trait:(class extends T1 with T2 with …
trait T1 { val a = 1 }
trait T2 { val b = 2 }
class SubClass extends T1 with T2
編譯會報錯:Error:(7, 7) class SubClass inherits conflicting members:
複合型別:
T1 with T2 with T3 ...
這種形式的型別-複合型別(compound type),或交集型別(intersection type)。
- 在方法宣告引數型別
def func (x: T1 with T2) = { println("hello") }
func(new T1 with T2)
- type宣告 複合型別:
type T = X1 with X2
def func (x: T) = { println("hello") }
- 複合型別中使用結構型別:
def func (x: X1 with X2 { def hello(): Unit }) = { println("hello") }