伴生对象中的隐式视图
我正在阅读 Joshua D. Suereth 的 Scala In Depth,并遇到了以下有关 scala 中隐式视图的代码:
object test {
trait Foo
trait Bar
object Foo {
implicit def fooToBar(f : Foo) = new Bar{ }
}
}
然后定义一个需要 Bar 作为参数的方法:
def bar(x : Bar) = println("bar")
为什么以下方法有效:
val f = new Foo{}
bar(f) // print "bar"
但
bar(new Foo{})
会导致编译器给出类型不匹配错误:
error: type mismatch;
found : java.lang.Object with test.Foo
required: test.Bar
bar(new Foo {})
^
I was reading Scala In Depth by Joshua D. Suereth, and came across the following code about implicit views in scala:
object test {
trait Foo
trait Bar
object Foo {
implicit def fooToBar(f : Foo) = new Bar{ }
}
}
Then define a method that requires a Bar as argument:
def bar(x : Bar) = println("bar")
Why the following works:
val f = new Foo{}
bar(f) // print "bar"
but
bar(new Foo{})
would cause the compiler to give type mismatch error:
error: type mismatch;
found : java.lang.Object with test.Foo
required: test.Bar
bar(new Foo {})
^
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是关于您正在做的事情的一些信息:
当您执行诸如
bar(new Foo {})
之类的操作时,编译器还不知道您在做什么 - 它会尝试找到一个bar
方法将接受new Foo {}
,但它还不知道new Foo {}
到底是什么类型,因为它取决于>栏
是。如果您声明
val f = new Foo{}
,f
的类型就会固定,然后帮助编译器找出应该对bar
执行的操作代码>.Here's something about what you are doing:
When you do something like
bar(new Foo {})
, the compiler doesn't know yet what you are doing -- it tries to find abar
method that will acceptnew Foo {}
, but it doesn't know yet exactly what typenew Foo {}
is, because it depends on whatbar
is.If you declare
val f = new Foo{}
,f
's type becomes fixed, which then helps the compiler find out what it should do aboutbar
.