java.lang.Boolean 到 scala.Boolean 问题

2022-01-19 00:00:00 scala boolean implicit-conversion java
georgii@gleontiev:~$ scala
Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val jbool = java.lang.Boolean.TRUE    
jbool: java.lang.Boolean = true

scala> val sbool = true         
sbool: Boolean = true

scala> def sboolMethod(sbool: Boolean) = print("got scala.Boolean " + sbool)              
sboolMethod: (sbool: Boolean)Unit

scala> sboolMethod(sbool)
got scala.Boolean true

scala> sboolMethod(jbool)
<console>:9: error: type mismatch;
 found   : java.lang.Boolean
 required: scala.Boolean
       sboolMethod(jbool)
                   ^

scala> implicit def jbool2sbool(bool: java.lang.Boolean): scala.Boolean = bool.booleanValue
jbool2sbool: (bool: java.lang.Boolean)Boolean

scala> sboolMethod(jbool)                                                                  
got scala.Boolean true

问题是:为什么没有从 java.lang.Booleanscala.Boolean 的默认隐式转换?该问题还代表 java.lang.Longscala.Long 以及可能的其他标准类型(还没有尝试过所有这些类型).

The question is: why isn't there a default implicit conversion from java.lang.Boolean to scala.Boolean? The question also stands for java.lang.Long vs scala.Long and probably other standard types (haven't tried all of them).

推荐答案

在 2.9 中,有这样的转换,大概是为了帮助与 Java 的互操作性.(Scala 自己不需要它,因为它透明地对基元进行装箱和拆箱,这可能是它之前没有被包含在内的原因.)

In 2.9, there is such a conversion, presumably to aid interoperability with Java. (Scala doesn't need it on its own, because it transparently boxes and unboxes primitives, which is perhaps why it wasn't included earlier.)

相关文章