如何在 scala 中使用 java.lang.Integer
我想使用静态方法Integer#bitCount(int)
。 但我发现我无法使用类型别名来实现它。类型别名和导入别名有什么区别?
scala> import java.lang.{Integer => JavaInteger}
import java.lang.{Integer=>JavaInteger}
scala> JavaInteger.bitCount(2)
res16: Int = 1
scala> type F = java.lang.Integer
defined type alias F
scala> F.bitCount(2)
<console>:7: error: not found: value F
F.bitCount(2)
^
I want to use the static method Integer#bitCount(int)
.
But I found out that I'm unable to use a type alias does to achieve it. What is the difference between a type alias an an import alias ?
scala> import java.lang.{Integer => JavaInteger}
import java.lang.{Integer=>JavaInteger}
scala> JavaInteger.bitCount(2)
res16: Int = 1
scala> type F = java.lang.Integer
defined type alias F
scala> F.bitCount(2)
<console>:7: error: not found: value F
F.bitCount(2)
^
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Scala 中,它没有使用静态方法,而是有配套的单例对象。
伴生单例对象的类型与伴生类不同,并且类型别名与类绑定,而不是与单例对象绑定。
例如,您可能有以下代码:
In Scala, instead of using static method, it has companion singleton object.
The companion singleton object's type is different to the companion class, and the type alias is bound with class, not the singleton object.
For example, you may have the following code:
您不能这样做,因为 F 是一种类型,而不是对象,因此没有静态成员。更一般地说,Scala 中没有静态成员:您需要在代表类的“静态组件”的单例对象中实现这些成员。
因此,在您的情况下,您需要直接引用 Java 类,以便 Scala 知道它可能包含静态成员。
You cannot do that because F is a type, and not an object, and has therefore no static member. More generally, there is no static member in Scala: you need to implement those in a singleton object that sort of represents the "static component" of the class.
As a result, in your case, you need to refer directly to the Java class so that Scala is aware that it may contain static members.
您可以像这样创建静态 java 方法的快捷方式
You could create a short cut to the static java method like this
F 是静态类型,它不是对象,也不是类。在 Scala 中,您只能向对象发送消息。
有什么区别Scala(和 Java)中的类和类型之间的关系?
F is a static type, it's not an object and it's not a class. In Scala you can only send messages to objects.
What is the difference between a class and a type in Scala (and Java)?