我想使用静态方法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)
^
答案 0 :(得分: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.
答案 1 :(得分:3)
你不能这样做,因为F是一个类型,而不是一个对象,因此没有静态成员。更一般地说, Scala中没有静态成员:您需要在单个对象中实现那些代表该类的“静态组件”的对象。
因此,在您的情况下,您需要直接引用Java类,以便Scala知道它可能包含静态成员。
答案 2 :(得分:2)
F是一个静态类型,它不是一个对象而且它不是一个类。在Scala中,您只能向对象发送消息。
class MyClass // MyClass is both a class and a type, it's a class because it's a template for objects and it's a type because we can use "MyClass" in type position to limit the shape of computations
type A = MyClass // A is a type, even if it looks like a class. You know it's a type and not a class because when you write "new A.getClass" what you get back is MyClass. The "new" operator takes a type, not a class. E.g. "new List[MyClass]" works but "new List" does not.
type B = List[MyClass] // B is a type because List[MyClass] is not a class
type C = List[_ <: MyClass] // C is a type because List[_ <: MyClass] is clearly not a class
What is the difference between a class and a type in Scala (and Java)?
答案 3 :(得分:2)
您可以像这样
创建静态java方法的捷径val bitCount:(Int) => Int = java.lang.Integer.bitCount