为什么在这种特定情况下Scala无法找到次要隐式值? [英] Why does Scala fail to find a secondary implicit value in this one particular case?

查看:88
本文介绍了为什么在这种特定情况下Scala无法找到次要隐式值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难解释 主隐式值或附加隐式值寻求的其他隐式值 隐式转换.具体来说,这可行:

I am having a hard time explaining the difference in behavior between additional implicit values sought by either a primary implicit value or an implicit conversion. Specifically, this works:

trait Foo[A]
implicit def fooString: Foo[String] = null

implicit def value[A](implicit foo: Foo[A]) = 5

> implicitly[Int]
5

但这不是:

implicit def conversion[A](x: Int)(implicit foo: Foo[A]) = new {
    def aMethod = 5
}

> 1.aMethod
could not find implicit value for parameter foo: test.Foo[A]

变化:

  • 搜索是通过implicitly还是隐式转换开始的
  • 所寻求的次要隐式值是否是多态的
  • 提供的辅助隐式值是否是多态的
  • Whether the search is started by implicitly or an implicit conversion
  • Whether the secondary implicit value sought after is polymorphic
  • Whether the secondary implicit value supplied is polymorphic

我得到以下结果:

Conversion/value  Searching for  Supplied | Works?
----------------  -------------  -------- | ------
     conversion     poly          poly    |  yes
     conversion     poly          mono    |  **no**
     conversion     mono          poly    |  yes
     conversion     mono          mono    |  yes
     value          poly          poly    |  yes
     value          poly          mono    |  yes
     value          mono          poly    |  yes
     value          mono          mono    |  yes

如您所见,唯一不起作用的情况是开始搜索时 通过隐式转换,寻求的值是多态的,但该值 提供的是单态的.

As you can see, the only case that does not work is when the search is started by an implicit conversion, the value sought is polymorphic, yet the value supplied is monomorphic.

是否存在理论上的原因,为什么? 错误/Scala的局限性?

Is there a theoretical reason why this should be the case, or is this a bug/limitation of Scala?

推荐答案

您正被scalac bug咬伤 SI-3346 .更一般而言,请参见 SI-4699 的说明.点(1),

You're being bitten by scalac bug SI-3346. More generally see the description of SI-4699, esp. point (1),

1)隐式搜索和隐式转换搜索以不同方式对待不确定的类型参数

1) implicit search and implicit conversion search treat undetermined type parameters differently

您要直接观察的情况是您的案例区分了隐式值和隐式转换.

which you're observing directly where your cases are distinguishing between implicit values and implicit conversions.

我已经更新了SI-3346,将其作为附加示例.

I've updated SI-3346 to include this as an additional example.

这篇关于为什么在这种特定情况下Scala无法找到次要隐式值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆