2011-02-25 21 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 
相關問題