简体   繁体   中英

asInstanceOf err in Scala

在此处输入图像描述

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")
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM