本文介绍了为什么在嵌套类型参数时 Scala 不能完全推断类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下 Scala 代码:
Consider the following Scala code:
abstract class A
abstract class B[T <: A]
class ConcreteA extends A
class ConcreteB extends B[ConcreteA]
class Example[U <: B[T], T <: A]( resolver: U )
object Test {
new Example( new ConcreteB )
}
最后一行 new Example( new ConcreteB )
编译失败,错误如下:
The last line new Example( new ConcreteB )
fails to compile with the following error:
错误:推断的类型参数 [ConcreteB,Nothing] 不符合类 Example 的类型参数边界 [U <: B[T],T <: A]
但是 ConcreteB
拥有解析 U 和 T 所需的所有数据.我在这里遗漏了什么?
But ConcreteB
has all the necessary data to resolve both U and T. What am I missing here?
推荐答案
Kipton 接近了他的高级解决方案.不幸的是,他被 Scala 中的一个 bug 绊倒了 <2.9.1.RC1.以下在 2.9.1.RC1 和主干上按预期工作,
Kipton got close with his higher-kinded solution. Unfortunately he tripped over what appears to be a bug in Scala < 2.9.1.RC1. The following works as expected with 2.9.1.RC1 and trunk,
Welcome to Scala version 2.9.1.RC1 (Java HotSpot(TM) Server VM, Java 1.7.0).
Type in expressions to have them evaluated.
Type :help for more information.
scala> abstract class A
defined class A
scala> abstract class B[T <: A]
defined class B
scala> class ConcreteA extends A
defined class ConcreteA
scala> class ConcreteB[T <: A] extends B[T]
defined class ConcreteB
scala> class Example[T <: A, U[X <: A] <: B[X]](resolver: U[T])
defined class Example
scala> new Example(new ConcreteB[ConcreteA])
res0: Example[ConcreteA,ConcreteB] = Example@ec48e7
这篇关于为什么在嵌套类型参数时 Scala 不能完全推断类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!