你如何在 Scala 中输入类型转换 Char/Int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4216308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you type cast Char/Int in Scala?
提问by CanisUrsa
I am having issues getting this cast to work.
我在让这个演员工作时遇到问题。
The compiler tells me value aNumberis not a member of object Char
编译器告诉我 valueaNumber不是 object 的成员Char
def runCastTest() {
val aNumber = 97
val aChar = (Char)aNumber
println(aChar) // Should be 'a'
}
What am I doing wrong?
我究竟做错了什么?
回答by fedesilva
You are not casting. With (Char)aNumberyou are trying to invoke a method aNumberin the object Char:
你不是在铸造。当(Char)aNumber您尝试调用aNumber对象 Char 中的方法时:
scala> val aNumber = 97
aNumber: Int = 97
scala> val aChar = (Char)aNumber
<console>:5: error: value aNumber is not a member of object Char
val aChar = (Char)aNumber
^
You can do
你可以做
scala> aNumber.asInstanceOf[Char]
res0: Char = a
or as Nicolas suggested call toCharon the Int instance:
或者像 Nicolas 建议调用toCharInt 实例:
scala> aNumber.toChar
res1: Char = a
回答by Nicolas
As everything is an Object in scala, you should use aNumber.toChar.
由于在 Scala 中一切都是对象,因此您应该使用aNumber.toChar.

