[英]Scala - Supertype of a type parameter
In Scala, how can I do something like this: 在Scala中,我该怎么做:
def cast [Type] (x: _ >: Type, errMsg: String): Type = {
if (x.isInstanceOf[Type]) {
x.asInstanceOf[Type]
} else {
throw new Exception(errMsg)
}
}
x: _ >: Type
(a notation that does not exist in Scala) meaning "the type of x is any supertype of Type". x: _ >: Type
(Scala中不存在的一种表示法),意思是“ x的类型是Type的任何超类型”。
If x can be of any superType of Type
, then certainly it can be Any
. 如果x可以是
Type
的任何superType,那么肯定可以是Any
。 This is no constraint at all, you can just write x : Any
完全没有限制,您可以只写
x : Any
On another line, due to type erasure, you x.isInstanceOf[Type]
will do no useful check. 在另一行上,由于类型擦除,您
x.isInstanceOf[Type]
将不做任何有用的检查。 You cannot check on a type parameter. 您无法检查类型参数。 (You have to ensure that the type information will be available at runtime. You can get to something with
Manifest
). (您必须确保类型信息在运行时可用。您可以使用
Manifest
)。
Try this: 尝试这个:
def cast[T >: Type](x: T, errMsg: String): T = { ... }
However, you might want to reconsider the necessity of explicit typecasts in Scala. 但是,您可能想重新考虑Scala中显式类型转换的必要性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.