[英]Is it possible to define a return type with an arbitrary type parameter?
Assume, we have aa class with an type parameter 假设我们有一个带有类型参数的类
class A[T]
And we want to write a method, that returns objects of the type A
with an arbritrary type parameter, like: 我们想编写一个方法,该方法返回带有Arbritrary类型参数的
A
类型A
对象,例如:
def f: A = { ... }
The compiler will complain about the missing type parameter for type A
. 编译器将抱怨类型
A
缺少类型参数。
We can not solve this problem by writing A[Any]
, since eg A[String]
is no subtype of A[Any]
. 我们无法通过编写
A[Any]
解决此问题,因为例如A[String]
不是A[Any]
子类型。 But we can reach this subtype relation with a covariant annotation of +T
. 但是我们可以使用
+T
的协变注释来达到此子类型关系。
Is it possible write such a method f
without using covariant annotation +T
? 是否可以在不使用协变注释
+T
情况下编写此类方法f
?
You can use existential types: 您可以使用存在类型:
def f: A[_] = { ... }
This is shorthand for: 这是以下内容的简写:
def f: A[T forSome { type T }] = { ... }
You can even use upper (or lower) bounds: 您甚至可以使用上限(或下限):
def f: A[_ <: SomeType] = { ... }
You can assign any type T
to this, however, you may not be able to do anything useful with the result 您可以为此指定任何类型
T
,但是您可能无法对结果执行任何有用的操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.