简体   繁体   English

是否可以使用任意类型参数定义返回类型?

[英]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.

相关问题 是否可以使用参数化类型定义返回类型 - Is it possible to define a return type with a parameterised type 参数类型还是返回类型作为参数? - Type of parameter or return type as parameter? 是否可以使用可变参数定义宏,并为每个参数获取一个类型? - Is it possible to define a macro with variadic parameters, and get a type for each parameter? 可以在Scala中找到参数类型方法返回类型,其中parameter是原始类型吗? - Possible to find parameter type methods return type in Scala where parameter is a primitive type? 如何将函数的返回类型指定为(任意)monad? - How to specify the return type of a function to be a (arbitrary) monad? 任意函数 - 根据输入生成返回类型 - Arbitrary Function - Generate return type according to input 是否可以根据函数参数类型定义的映射来定义函数返回类型? - Is it possible to define a function return type based on a defined mapping from the type of a function argument? 如何定义类型参数,该参数可以是类型,也可以是该类型的容器? - How to define a type parameter that can be either a type or a container for that type? Scala 按类型参数过滤并返回构造返回类型和类型构造函数 - Scala filter by type parameter and return construct return type with type constructor 具有逆变类型参数的继承返回类型 - Inherited return type with contravariant type parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM