隐式参数中断类型推断还是不足以解决它们的解析? [英] Implicit parameters break type inference or inference does not suffice for their resolution?
问题描述
类型推断在此示例中工作正常.类型推断规则(从左到右以及跨参数列表)似乎很满意,但是关于隐式的某些事情打破了它.
Type inference works fine in this example until I add the implicit ordering evidence. Type inference rules (from left to right & across parameter lists) seem to be satisfied, but there is something in regards to the implicit that breaks it.
case class Insert[I, O : Ordering](arg: I)
def execute[I,O](req: Insert[I,O]): O = null.asInstanceOf[O]
val result: Int = execute(Insert("test"))
Error:(5, 39) diverging implicit expansion for type Ordering[O]
starting with method Tuple9 in object Ordering
lazy val result: Int = execute(Insert("test"));}
^
这可以编译并正常工作:
This compiles and works fine:
case class Insert[I, O](arg: I)
def execute[I,O](req: Insert[I,O]): O = null.asInstanceOf[O]
val result: Int = execute(Insert("test"))
因此,要么类型推断不足以实现隐式解析,要么隐式解析破坏了类型推断.
So either type inference isn't sufficient for implicit resolution OR implicit resolution breaks type inference.
我猜想推断出O
类型,但是当发生隐式解析时,它将视为Nothing,换句话说,它将视为我未在val result: Int
中指定Int
.是虫子吗?
I guess the O
type is inferred but when implicit resolution is happening, it sees it as Nothing, in other words, it sees it as if I didn't specified Int
in val result: Int
. Is it a bug?
推荐答案
此处的问题是scala无法推断O
类型,因为它不在Insert
The issue here is that scala cannot infer the O
type because it is not present in Insert
// I is in the parameter list but there is no O to be found
case class Insert[I, O](arg: I)(implicit evidence: Ordering[O])
这使编译器别无选择,只能推断O
为Nothing
.创建Insert
的实例将无法编译.
This leaves the compiler no choice but to infer O
to be Nothing
. Creating an instance of Insert
will then fail to compile.
scala> val i = Insert(3)
<console>:9: error: diverging implicit expansion for type Ordering[O]
starting with method Tuple9 in object Ordering
val i = Insert(3)
diverging implicit expansion
错误是Scala试图找到适用于这种情况的隐式函数,并陷入了循环之中.这是一条红鲱鱼.
The diverging implicit expansion
error is scala attempting to find an implicit that works for this case and getting caught in a cycle. It is a red herring.
这篇关于隐式参数中断类型推断还是不足以解决它们的解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!