2011-02-25 69 views
3

我想使用静态方法Integer#bitCount(int)。 但我发现我无法使用类型别名来实现它。一个类型别名和一个导入别名有什么区别?如何在内部scala中使用java.lang.Integer

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) 
    ^
+5

静态Java方法这个最近的问题可能会有所帮助:http://stackoverflow.com/questions/5031640/what -is最差之间-A级 - 和 - a型在-阶和 - 爪哇。 – huynhjl 2011-02-25 07:48:01

+0

如果你想把它称为'F',为什么不把它作为'{Integer => F}'来导入? – 2011-02-25 17:20:12

回答

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. 
+0

那么通过导入,scala会引入类&automagically伴侣对象? – 2011-02-25 12:30:17

+0

不,C不是“class MyClass”。 C是一种类型,而不是一类。您也可以编写C = List [MyClass]类型,但List [MyClass]不是类。这是一种类型。 – 2011-02-25 15:40:22

3

你不能这样做,因为F是一个类型,而不是一个对象,并有因此没有静态成员。更一般的说,在Scala中没有静态成员:你需要在一个代表类的“静态组件”的单类对象中实现它们。

因此,对于您的情况,您需要直接引用Java类,以便Scala知道它可能包含静态成员。

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)?

2

您可以创建一个快捷方式到这样

val bitCount:(Int) => Int = java.lang.Integer.bitCount 
相关问题