Why doesn't type inference work here?

試著忘記壹切 提交于 2019-12-05 07:44:40

This isn't a Scala compiler bug, but it's certainly a limitation of Scala's type inference. The compiler wants to determine the bound on X, S[T], before solving for X, but the bound mentions the so far unconstrained type variable T which it therefore fixes at Nothing and proceeds from there. It doesn't revisit T once X has been fully resolved ... currently type inference always proceeds from left to right in this sort of case.

If your example accurately represents your real situation then there is a simple fix,

def apply[T](x : S[T]) = x.doSomething

Here T will be inferred such that Minimal conforms to S[T] directly rather than via an intermediary bounded type variable.

Update

Joshua's solution also avoids the problem of inferring type T, but in a completely different way.

def apply[T, X <% S[T]](x : X) = x.doSomething

desugars to,

def apply[T, X](x : X)(implicit conv : X => S[T]) = x.doSomething

The type variables T and X can now be solved for independently (because T is no longer mentioned in X's bound). This means that X is inferred as Minimal immediately, and T is solved for as a part of the implicit search for a value of type X => S[T] to satisfy the implicit argument conv. conforms in scala.Predef manufactures values of this form, and in context will guarantee that given an argument of type Minimal, T will be inferred as Int. You could view this as an instance of functional dependencies at work in Scala.

There's some weirdness with bounds on structural types, try using a view bound on S[T] instead.

def apply[T, X <% S[T]] (x: X) = x.doSomething works fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!