In Scala, how can I do something like this:
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".
If x can be of any superType of Type
, then certainly it can be Any
. This is no constraint at all, you can just write x : Any
On another line, due to type erasure, you x.isInstanceOf[Type]
will do no useful check. 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
).
Try this:
def cast[T >: Type](x: T, errMsg: String): T = { ... }
However, you might want to reconsider the necessity of explicit typecasts in Scala.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.