prosseek
prosseek

Reputation: 190799

Use variable for type checking code in Scala

I have a code that a AnyVal type data f should be converted into Float/Double depending on the input parameter.

    if (n == 4) {
      if (f.asInstanceOf[Float].isNaN) None
      else Some(f)
    } else {
      if (f.asInstanceOf[Double].isNaN) None
      else Some(f)
    }

I tried to use variable to get this code, but I have an error.

    val t = if (n == 4) classOf[Float] else classOf[Double]
    if (f.asInstanceOf[t].isNaN) None
    else Some(f)

enter image description here

What might be wrong?

Upvotes: 1

Views: 77

Answers (2)

Ende Neu
Ende Neu

Reputation: 15783

t here has type Class[_ >: Float with Double <: AnyVal] because scala find the common super type to classOf[Float] and classOf[Double], also as Alexey Romanov pointed out, t is a variable while asInstanceOf takes a type parameter, easy solution would be this:

val t: Option[Double] = 
  if (n == 4) Option(f.asInstanceOf[Float]) else Option(f.asInstanceOf[Double])

Which returns a Option[Double] since Double is a common supertype(*) to Float, for a more complex solution where you bring along the type in a variable I can't help you.

(*) it is not really a supertype but Scala has a view from Float to Double.

Upvotes: 2

Alexey Romanov
Alexey Romanov

Reputation: 170735

t is a value, not a type, and the square brackets after asInstanceOf indicate it takes a type parameter. You can't have a variable type like this (there is such a thing as type variables, but they won't be useful here). One possible workaround is given in Ende Neu's answer; another would be

t.cast(f)

but this won't work here because you won't be able to call isNaN on the result.

Upvotes: 2

Related Questions