伴随对象中的隐式视图(Implicit views in companion object)

编程入门 行业动态 更新时间:2024-10-25 16:21:14
伴随对象中的隐式视图(Implicit views in companion object)

我正在阅读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 {}) ^

最满意答案

这是关于你在做什么的事情:

new Foo {} // Anonymous subclass of Object with trait Foo new Foo () // Foo new Foo // Foo

当你做bar(new Foo {})这样的事情时,编译器还不知道你在做什么 - 它试图找到一个接受new Foo {}的bar方法,但它还不知道究竟是什么键入new Foo {} ,因为它取决于什么是bar 。

如果声明val f = new Foo{} ,则f的类型变得固定,这有助于编译器找出它应该对bar做什么。

Here's something about what you are doing:

new Foo {} // Anonymous subclass of Object with trait Foo new Foo () // Foo new Foo // Foo

When you do something like bar(new Foo {}), the compiler doesn't know yet what you are doing -- it tries to find a bar method that will accept new Foo {}, but it doesn't know yet exactly what type new Foo {} is, because it depends on what bar is.

If you declare val f = new Foo{}, f's type becomes fixed, which then helps the compiler find out what it should do about bar.

更多推荐

本文发布于:2023-08-02 17:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1378736.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   象中   隐式   Implicit   companion

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!