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 beAny. This is no constraint at all, you can just writex : AnyOn 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 withManifest).