Class 有自己的上下文绑定
Class with its own context bound
以下作品:
trait Context[T] {
def context(x: T): String
class Foo[T : Context](x: T) {
def bar() = implicitly[Context[T]].context(x)
}
implicit val c = new Context[Double] {
override def context(x: Double): String = "I am a double"
}
val f = new Foo(2.0)
f.bar() // I am a double
所以我想...如果我构造一个 class 里面有自己的 Context 定义是不是也可以?
object Foo {
def apply[T : Context](x: T) = new Foo[T](x)
def apply[T](x: T, contextFunc: T => String): Foo[T] with Context[T] = new Foo[T](x) with Context[T] {
override def context(x: T): Double = contextFunc(x)
}
}
val f2 = Foo[Double](2.0, x => "I am still a double")
但它开始抱怨第二个应用函数中缺少隐含证据。我可以想象,因为看起来它首先开始制作 Foo-class 然后开始制作 Context[T] 特征。
有办法解决吗?换一种说法?有没有办法构造一个拥有自己的 Context[T] 的 Foo class?
最简单的方法可能是构造一个上下文对象并将其作为参数显式传递,在构造 Foo
:
时
def apply[T](x: T, contextFunc: T => String): Foo[T] =
new Foo(x)(new Context[T] {
def context(t: T) = contextFunc(t)
})
以下作品:
trait Context[T] {
def context(x: T): String
class Foo[T : Context](x: T) {
def bar() = implicitly[Context[T]].context(x)
}
implicit val c = new Context[Double] {
override def context(x: Double): String = "I am a double"
}
val f = new Foo(2.0)
f.bar() // I am a double
所以我想...如果我构造一个 class 里面有自己的 Context 定义是不是也可以?
object Foo {
def apply[T : Context](x: T) = new Foo[T](x)
def apply[T](x: T, contextFunc: T => String): Foo[T] with Context[T] = new Foo[T](x) with Context[T] {
override def context(x: T): Double = contextFunc(x)
}
}
val f2 = Foo[Double](2.0, x => "I am still a double")
但它开始抱怨第二个应用函数中缺少隐含证据。我可以想象,因为看起来它首先开始制作 Foo-class 然后开始制作 Context[T] 特征。
有办法解决吗?换一种说法?有没有办法构造一个拥有自己的 Context[T] 的 Foo class?
最简单的方法可能是构造一个上下文对象并将其作为参数显式传递,在构造 Foo
:
def apply[T](x: T, contextFunc: T => String): Foo[T] =
new Foo(x)(new Context[T] {
def context(t: T) = contextFunc(t)
})