简体   繁体   中英

How do I use java.lang.Integer inside scala

I want to use the static method Integer#bitCount(int) . But I found out that I'm unable to use a type alias does to achieve it. What is the difference between a type alias an an import 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)
       ^

In Scala, instead of using static method, it has companion singleton object.

The companion singleton object's type is different to the companion class, and the type alias is bound with class, not the singleton object.

For example, you may have the following code:

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.

You cannot do that because F is a type, and not an object, and has therefore no static member. More generally, there is no static member in Scala : you need to implement those in a singleton object that sort of represents the "static component" of the class.

As a result, in your case, you need to refer directly to the Java class so that Scala is aware that it may contain static members.

F is a static type, it's not an object and it's not a class. In Scala you can only send messages to objects.

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

您可以像这样创建静态java方法的快捷方式

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM