2012-02-24 82 views

回答

6

我认为,结构类型是你所需要的:

trait MyTrait { 
    self: { val bar: String } => 
def showBar = bar 
} 

class Foo(val bar: String) extends MyTrait 
+0

你好,谢谢你的回复!是否有可能将Foo中的字段暴露给MyTrait _in_ Foo? – aef 2012-02-24 19:37:35

+0

我不太了解你的想法。我想,你的多态特质的原始解决方案就是它。我的第二个猜测是,如果你想要更复杂的(scala-way)依赖注入,请查看[subcut](https://github.com/dickwall/subcut)库。 – 4e6 2012-02-25 07:43:32

1

它已经工作。

scala> trait Foo[A] { self: A => 
    | } 
defined trait Foo 

scala> class Meh extends Foo[Meh] 
defined class Meh 

scala> class Duh extends Foo[Meh] 
<console>:36: error: illegal inheritance; 
self-type Duh does not conform to Foo[Meh]'s selftype Foo[Meh] with Meh 
     class Duh extends Foo[Meh] 
         ^

编辑:

对不起,我误解了这个问题。 @ 4e6是对的。你需要一个结构类型。他的解决方案的细微变化:

scala> trait Foo[A <: { def bar: String }] { self: A => 
    | } 
defined trait Foo 

scala> class Bar extends Foo[Bar] { 
    | def bar = "" 
    | } 
defined class Bar 

scala> class Baz extends Foo[Baz] 
<console>:35: error: type arguments [Baz] do not conform to trait Foo's type parameter bounds [A <: AnyRef{def bar: Stri 
ng}] 
     class Baz extends Foo[Baz] 
         ^
相关问题