elm
elm

Reputation: 20405

Scala type casting

In Scala, given an Object

scala> f.get(c)
res1: Object = 1

and

scala> f.getType
res3: Class[_] = int

how to get

val a = 1

where a is of type Int, and where the type is known only from f.getType.

Upvotes: 1

Views: 1347

Answers (1)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

You don't. Say you have this:

f.getType match {
  case x if x ifAssignableFrom classOf[Int] =>
    val a = f.get(c).asInstanceOf[Int]
}

There are two problems with it. First, it uses asInstanceOf, which you should never do. Second, the scope of val a is the case statement. A slightly better approach would be this:

f.get(c) match {
  case a: Int =>
}

This is better, because a will only be an Int if it is really an Int. The information from f.getType is basically useless, because it might be true or not, while the actual type is always true.

Still, the scope is limited, and it really cannot be any other way. When you say val a: Int = f.get(c), you are declaring at compile time, that a will always be Int from that point forward, until the end of its scope.

Meanwhile, the return type of f.get(c) and f.getType is information present at run time, that is, after the program has been compiled.

If you need to do this, use the second alternative, but, instead, try to find a different design that does not require this sort of thing.

Upvotes: 2

Related Questions