在本示例中,如何从深度的Scala中隐式地工作 [英] How does implicitly work in this example from Scala in Depth
问题描述
在《深度学习Scala》一书中.有一个隐式作用域示例,如下所示:
In the book Scala in Depth . There's this example of implicit scoping as follows:
scala> object Foo {
| trait Bar
| implicit def newBar = new Bar {
| override def toString = "Implicit Bar"
| }
| }
defined module Foo
scala> implicitly[Foo.Bar]
res0: Foo.Bar = Implicit Bar
我的问题是在上面给出的示例中如何隐式地找到trait Bar的实现?我对隐式工作方式感到困惑
My question here is how did implicitly find the implementation of the trait Bar in the above given example? I think I am a little confused by how implicitly works
推荐答案
显然,对于Foo.Bar,它的工作方式类似于Foo#Bar,即if T is a type projection S#U, the parts of S as well as T itself
处于隐式范围内(该规范的7.2,但请参阅常规资源在隐式范围内(例如您已经在咨询). (更新:这里就是这样的资源.它并不能完全说明这一点.案例,以及一个真实的示例是否看起来像是虚假的.)
Apparently, for Foo.Bar, it works like Foo#Bar, i.e., if T is a type projection S#U, the parts of S as well as T itself
are in implicit scope (7.2 of the spec, but see usual resources on implicit scope, such as you're already consulting). (Update: Here is such a resource. It doesn't illustrate exactly this case, and whether a real example would look as artificial.)
object Foo {
trait Bar
implicit def newBar = new Bar {
override def toString = "Implicit Bar"
}
}
class Foo2 {
trait Bar
def newBar = new Bar {
override def toString = "Implicit Bar"
}
}
object Foo2 {
val f = new Foo2
implicit val g = f.newBar
}
object Test extends App {
// expressing it this way makes it clearer
type B = Foo.type#Bar
//type B = Foo.Bar
type B = Foo2#Bar
def m(implicit b: B) = 1
println(implicitly[B])
println(m)
}
这篇关于在本示例中,如何从深度的Scala中隐式地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!