1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I missed the variable part.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.