我尝试定义这样一个简单的特征:
scala> trait T { def p[A,B]: Map[A,B] }
defined trait T
scala> new T { def p = Map(0 -> 1) }
<console>:7: error: object creation impossible, since method p in trait T of type [A,B]Map[A,B] is not defined
new T { def p = Map(0 -> 1) }
^
Run Code Online (Sandbox Code Playgroud)
怎么会?
谢谢
Ran*_*ulz 10
您可以使用泛型方法,但抽象泛型方法的实现本身必须是通用的:
scala> trait T { def p[A,B]: Map[A,B] }
defined trait T
scala> new T { def p[S, T] = Map[S, T]() }
res13: java.lang.Object with T = $anon$1@1f74864
Run Code Online (Sandbox Code Playgroud)
请记住,无界类型参数是普遍量化的.你说p是为所有类型对定义的,没有异常或约束.许多S和T绑定与Int不兼容,因此您不能只返回需要Map [S,T]的Map [Int,Int].
更新: Re:"所以我可以使用泛型抽象类和特征的非泛型实现,但不能使用泛型方法吗?"
在这个意义上,您可以使用泛型抽象类的非泛型实现:
abstract class C[A, B, C] { /* ... */ }
class D extends C[Int, String, Boolean] { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
或者像这样:
class E extends C { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
虽然那个与以下相同:
class E extends C[Nothing, Nothing, Nothing] { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
并且Nothing是Scala中无人居住的类型.
但是您无法使用非泛型方法实现抽象泛型方法
| 归档时间: |
|
| 查看次数: |
2811 次 |
| 最近记录: |