Scala隐式解析机制是否与声明顺序有关? [英] Scala implicits resolution mechanism is declaration order dependent?
问题描述
在每天的Scala编码过程中,我遇到一个问题,即Scala隐式解析取决于声明顺序.一个简单的例子:
During daily Scala coding I faced an issue that Scala implicits resolution depends on declaration order. A simple example:
object example extends App {
trait FooTypeClass[T] {
def foo: T
}
def bar[T](implicit tc: FooTypeClass[T]) = println(tc.foo)
class A {
// bar[A] doesn't compile
}
object A {
implicit object aFoo extends FooTypeClass[A] {
def foo: A = new A { override def toString = "a" }
}
}
bar[A]
}
它确实可以编译,但是如果我取消注释注释行,它将找不到作用域中所需的隐式对象.因此,要使其编译,应在class A
之前放置object A
声明.这意味着我的同伴应该去上他们的课,但是我宁愿离开他们,就像在示例中一样.
It does compile, but if I uncomment the commented line, it won't find the required implicit in scope. So, to make it compile I should place object A
declaration before class A
. That means my companions should go before their classes but I'd rather leave them as they are in the example.
为什么这个顺序很重要?有解决方法吗?
Why does this order matter? Is there a workaround for this?
推荐答案
一种可能的解决方法,可以保持您希望的顺序:
A possible workaround keeping the order you wished:
object A {
implicit val aFoo: FooTypeClass[A] = new FooTypeClass[A] {
def foo: A = new A {
override def toString = "a"
}
}
}
我一直在寻找为什么object
(而不是val
)不合适的解释.
I keep on seeking for the explanation why object
(instead of val
) doesn't fit.
这篇关于Scala隐式解析机制是否与声明顺序有关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!