键入上限和继承

时间:2014-02-17 23:15:47

标签: scala

假设我们有一个类Pair和一些继承树:

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 */

2 个答案:

答案 0 :(得分:1)

也许这会有所帮助:

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

答案 1 :(得分:1)

可能的解决方案如下:

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

  def sizeRelationship = r.compareTo(t)
}

请注意可查看 - &lt;%代替子类型 - &lt;: < / p>

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 */

与原始代码的主要区别在于,代替继承(实现)Comparable特征,域类通过implicit class进行改装。这使得可以展示类型签名所需的多态行为:

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

主要的实际优势与在Pair实例中使用基本类型签名的解决方案:

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

可以更准确地键入Pair实例,从而可以实现更复杂的下游处理(例如模式匹配等)。