2014-02-17 107 views
1

假設我們有一個類對和繼承的一些樹:類型上限和繼承

class Pair[ T <: Comparable[T] ](r:T,t:T) { 

    def sizeRelationship = r.compareTo(t) 
} 

sealed class Person(val importance:Int) extends Comparable[Person] { 
    override def compareTo(o: Person): Int = ??? 
} 

class Student extends Person(10) 
class Teacher extends Person(50) 

現在如何修改上面能夠打造一雙[學生]:?

val mixed: Pair[Person] = new Pair(new Student,new Teacher) /* compiles */ 
val notMixed = new Pair[Student](new Student, new Student) /* Student does not conform to Comparable */ 
+0

尋找線索:http://docs.scala-lang.org/tutorials/tour/lower-type-bounds.html – Ashalynd

+3

你不能創建_any_'Pair [Student]',因爲'Student'違反了類型'對''T'的要求。 '學生不是<:可比[學生]',但只有'<:可比[人]'。 –

回答

1

也許這會有所幫助:

val notMixed = new Pair(new Student, (new Student).asInstanceOf[Person]) 
1

一個可能的解決方案是:

class Pair[ T <% Comparable[T] ](r:T,t:T) { 

    def sizeRelationship = r.compareTo(t) 
} 

注意可見,爲<%到位亞型的的<:

sealed class Person(val importance:Int) { 
    def compareTo(o: Person): Int = ??? 
} 

class Student extends Person(10) 
class Teacher extends Person(50) 

implicit class PersonComparable[T <: Person](x: T) extends Comparable[T] { 
    def compareTo(o: T): Int = x.compareTo(o) 
} 

val mixed: Pair[Person] = new Pair(new Student,new Teacher) /* compiles */ 
val notMixed = new Pair[Student](new Student, new Student) /* compiles */ 

與原始代碼的主要區別是,在發生繼承(實現)的可比性狀,域類改裝它,通過implicit class的手段。這使得有可能表現出由類型簽名所需的多態行爲:

val notMixed = new Pair[Student](...) 

主要的實際優點與在所述一對例如使用基類型簽名的溶液:

val notMixed = new Pair[Person](...) 

更準確地輸入Pair實例,從而可以實現更復雜的下游處理(例如模式匹配等)。