我如何在scala中使用java.lang.Integer

Fra*_*ery 3 java scala

我想使用静态方法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)
       ^
Run Code Online (Sandbox Code Playgroud)

Bri*_*Hsu 7

在Scala中,它不是使用静态方法,而是具有伴随单例对象.

伴随单例对象的类型与伴随类不同,类型别名与类绑定,而不是单例对象.

例如,您可能具有以下代码:

class MyClass {
    val x = 3;
}

object MyClass {
    val y = 10;
}

type C = MyClass // now C is "class MyClass", not "object MyClass"
val myClass: C = new MyClass() // Correct
val myClassY = MyClass.y // Correct, MyClass is the "object MyClass", so it has a member called y.
val myClassY2 = C.y // Error, because C is a type, not a singleton object.
Run Code Online (Sandbox Code Playgroud)