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

如何在scala中使用java.lang.Integer,java,scala,Java,Scala,我想使用静态方法Integer#bitCount(int)。 但我发现我无法使用alias的类型来实现它。类型别名和导入别名之间有什么区别 scala> import java.lang.{Integer => JavaInteger} import java.lang.{Integer=>JavaInteger} scala> JavaInteger.bitCount(2) res16: Int = 1 scala> type F = java.lang.In

我想使用静态方法
Integer#bitCount(int)
。 但我发现我无法使用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)
       ^
scala>import java.lang.{Integer=>JavaInteger}
导入java.lang.{Integer=>JavaInteger}
scala>JavaInteger.bitCount(2)
res16:Int=1
scala>类型F=java.lang.Integer
定义的类型别名F
scala>F.bitCount(2)
:7:错误:未找到:值F
F.比特数(2)
^

在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.

您不能这样做,因为F是一个类型,而不是一个对象,因此没有静态成员。更一般地说,Scala中没有静态成员:您需要在某种程度上表示类的“静态组件”的单例对象中实现这些成员


因此,在您的例子中,您需要直接引用Java类,以便Scala知道它可能包含静态成员

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
class MyClass//MyClass既是一个类也是一个类型,它是一个类,因为它是对象的模板,它是一个类型,因为我们可以在类型位置使用“MyClass”来限制计算的形状
type A=MyClass//A是一个类型,即使它看起来像一个类。你知道它是一个类型而不是一个类,因为当你写“newa.getClass”时,你得到的是MyClass。“new”运算符采用类型,而不是类。例如,“新列表[MyClass]”有效,但“新列表”无效。
类型B=列表[MyClass]//B是一个类型,因为列表[MyClass]不是一个类

类型C=List[\up>您可以创建一条通向静态java方法的捷径,如下所示

val bitCount:(Int) => Int = java.lang.Integer.bitCount

最近的这个问题可能会有帮助:。如果你想把它称为
F
,为什么不把它作为
{Integer=>F}
导入呢?因此,通过导入,scala自动引入了类&伴随对象?不,C不是“类MyClass”。C是一个类型,不是类。你也可以编写类型C=List[MyClass],而是List[MyClass]不是类,而是类型。