简体   繁体   English

Scala中的asInstanceOf错误

[英]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 . 1true ,因为1属于Int类型,而true属于Boolean类型。 Scala is strongly typed so it doesn't automatically convert between these two types, unlike languages such as C and Python. Scala 是强类型的,因此它不会自动在这两种类型之间进行转换,这与 C 和 Python 等语言不同。

To fix it, just convert the Int to a Boolean like this:要修复它,只需将Int转换为Boolean ,如下所示:

val x1 = x != 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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