2014-02-17 152 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实例,从而可以实现更复杂的下游处理(例如模式匹配等)。