是否可以将特征的上下文更改为声明为其类型参数的类型?

问题描述:

我想什么来实现类似于这样:是否可以将特征的上下文更改为声明为其类型参数的类型?

class Foo(val bar: String = "Hello!") extends MyTrait[ Foo ] 

trait MyTrait[ T ] { self : T => 
T.bar 
} 

改变自我:T自我:美孚明显的作品,但MyTrait再延长类,也有吧,这样自嘲:富ISN”吨可以接受。

我可能会谈论这个错误,任何想法?

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

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

它已经工作。

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] 
         ^