Home > Back-end >  asInstanceOf erro
asInstanceOf erro

Time:07-16

enter image description here

why it is give me an error

I already write the code correctly

code :

    x = 1 //true
    val x1 = x.asInstanceOf[Boolean]
    if (x1) {
      println(s"Hello, $x1")
    }

CodePudding user response:

The problem is that the comment on this line is not correct:

x = 1 // true

1 is not true because 1 is of type Int and true is of type Boolean. Scala is strongly typed so it doesn't automatically convert between these two types, unlike languages such as C and Python.

To fix it, just convert the Int to a Boolean like this:

val x1 = x != 0
  • Related