特质如何引用实施类?

时间:2014-04-03 06:10:39

标签: scala

例如,我想声明一个有效的特征,"如果类C实现了这个特性,它有一个方法m,它返回一个类{{1}的实例}}"

我能想到的所有方式只是说C返回一个具有该特征的实例,这根本不是我想要的。

2 个答案:

答案 0 :(得分:4)

你像这样约束“自我类型”:

scala> trait Foo[Self] { self:Self => def m:Self }
defined trait Foo

scala> class A extends Foo[A] { def m = new A }
defined class A

scala> class B extends Foo[A] { def m = new B }
<console>:27: error: illegal inheritance;
 self-type B does not conform to Foo[A]'s selftype Foo[A] with A
       class B extends Foo[A] { def m = new B }
                       ^
<console>:27: error: type mismatch;
 found   : B
 required: A
       class B extends Foo[A] { def m = new B }
                                        ^

scala> class B extends Foo[B] { def m = new A }
<console>:27: error: type mismatch;
 found   : A
 required: B
       class B extends Foo[B] { def m = new A }

答案 1 :(得分:1)

如果我理解你的问题,你必须要找到这样的东西:

trait Foo[T] {
  def m: T
}

class A extends Foo[A] {
  def m = {
    getInstanceOfAFromSomewhere()
  }
}

class B extends Foo[B] {
  def m = {
    getInstanceOfBFromSomewhere()
  }
}

测试:

object Test extends App {
  val a: Foo[_] = new A
  println(a.m)

  val b: Foo[_] = new B
  println(b.m)
}

输出:

A@3d246f44
B@14a1373f

希望这就是你要找的东西