什么是Scala中的类型投影有用?为什么Scala的类型系统支持类型投影和路径依赖类型?这个设计决定背后的理由是什么?
请考虑以下Scala代码:
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 )
}
Run Code Online (Sandbox Code Playgroud)
最后一行new Example( new ConcreteB )无法编译,出现以下错误:
错误:推断类型参数[ConcreteB,Nothing]不符合类Example的类型参数bounds [U <:B [T],T <:A]
但是ConcreteB有解决U 和 T的所有必要数据.我在这里缺少什么?
当我尝试编译小例子时:
trait Foo[A,B] {
type F[_,_]
def foo(): F[A,B]
}
class Bar[A,B] extends Foo[A,B] {
type F[D,E] = Bar[D,E]
def foo() = this
}
object Helper {
def callFoo[A,B,FF <: Foo[A,B]]( f: FF ): FF#F[A,B] =
f.foo()
}
object Run extends App {
val x = new Bar[Int,Double]
val y = Helper.callFoo(x)
println( y.getClass )
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
[error] src/Issue.scala:20: inferred type arguments
[Nothing,Nothing,issue.Bar[Int,Double]] do not conform to method callFoo's type
parameter bounds [A,B,FF <: issue.Foo[A,B]]
[error] val y = Helper.callFoo(x) …Run Code Online (Sandbox Code Playgroud)