【问题标题】:How do I use java.lang.Integer inside scala如何在 scala 中使用 java.lang.Integer
【发布时间】:2011-07-04 02:10:10
【问题描述】:

我想使用静态方法Integer#bitCount(int)。 但我发现我无法使用类型别名来实现它。类型别名和导入别名有什么区别?

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

【问题讨论】:

标签: java scala


【解决方案1】:

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

【讨论】:

  • 所以通过导入,scala 正在引入类并自动成为伴生对象?
  • 不,C 不是“MyClass 类”。 C 是一个类型,而不是一个类。你也可以写类型 C = List[MyClass],但 List[MyClass] 不是一个类。这是一种类型。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2011-10-22
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 2013-10-21
        • 2011-04-11
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多