I'm new to scala, sorry for the dumb question. I want to remove the return statements from this Scala code (my real case is much more complicated than this)
def readValue[Type](value: Any)(implicit tag: ClassTag[Type]): Type = {
if (value == null) {
return null.asInstanceOf[Type]
} else {
if (classOf[URL].isAssignableFrom(tag.runtimeClass)) {
return new URL(value.toString).asInstanceOf[Type]
}
if (classOf[URI].isAssignableFrom(tag.runtimeClass)) {
return new URI(value.toString).asInstanceOf[Type]
}
null.asInstanceOf[Type]
}
}
that's why I want to store the return value of a Type instance, like this:
def readValue[Type](value: Any)(implicit tag: ClassTag[Type]): Type = {
var retVal:Type = null
if (value == null) {
// retVal=...
}
else {
// if cond: retVal=...
}
retVal
}
The solution above does not compile.
How could I initialize the variable for type Type
?
if-else
s are expressions, not just statements in scala:Also note that
classOf[A].isAssignableFrom(classOf[B])
means that a valueb
of typeB
can be downcast tob.asInstanceOf[A]
, not the other way round. IfclassOf[URL].isAssignableFrom(tag.runtimeClass)
, then you are allowed to cast a value of typeType
intoURL
, not the other way round.Moreover, your code would work if you restricted the argument
Type
toType >: Null
.