How to use java.lang.Integer inside scala

I want to use a static method Integer#bitCount(int). But I found that I cannot use the type alias to achieve it. What is the difference between an alias of type 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)
       ^
+3
source share
4 answers

In Scala, instead of using a static method, it has a single-user companion object.

The type of a singleton companion object is different from the companion class, and the type alias is associated with the class, not the single object.

For example, you might 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.
+7
source

, F - , , . Scala: , , " " .

Java, Scala , .

+3

F - , , . Scala .

class MyClass  // MyClass is both a class and a type, it a class because it a template for objects and it 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 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

Scala ( Java)?

+2

java-,

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

Source: https://habr.com/ru/post/1794629/


All Articles