java - 试图在 Java 中初始化 Scala 创建的类

标签 java scala jvm

我正在尝试学习 Scala,所以我决定用它来实现数据结构。我从 Stack 开始。我创建了以下 Stack 类。

class Stack[A : Manifest]() {

  var length:Int = -1
  var data = new Array[A](100)

  /**
   * Returns the size of the Stack.
  * @return the size of the stack
  */
 def size = {length} 

  /**
   * Returns the top element of the Stack without
   * removing it.
   * @return Stacks top element (not removed)
   */
  def peek[A] = {data(length)}

  /**
   * Informs the developer if the Stack is empty.
   * @return returns true if it is empty else false.
   */
  def isEmpty = {if(length==0)true else false}

  /**
   * Pushes the specified element onto the Stack.
   * @param The element to be pushed onto the Stack
   */
  def push(i: A){
    if(length+1 == data.size) reSize
    length+=1
    data(length) = i;
  }

  /**
   * Pops the top element off of the Stack.
   * @return the pop'd element.
   */
  def pop[A] = {
    length-=1
    data(length)
  }

  /**
   * Increases the size of the Stack by 100 indexes.
   */
  private def reSize{
    val oldData = data;
    data = new Array[A](length+101)
    for(i<-0 until length)data(i)=oldData(i)
   }
}

然后我尝试使用以下方法在我的 Java 类中初始化这个类

Stack<Integer> stack = new Stack<Integer>();

但是,我被告知构造函数不存在,我应该添加一个参数来匹配 Manifest。为什么会发生这种情况,我该如何解决?

最佳答案

Alexey 给了你正确的解释,但绝对可以在你的代码中创建 list (你只需要一个 java.lang.Class 对象,你可以在 Java 中轻松创建它)。

首先,您应该向 Stack 的伴随对象添加一个 java 友好的工厂方法:

object Stack {
  def ofType[T]( klass: java.lang.Class[T] ) = {
    val manifest =  new Manifest[T] {
      def erasure = klass
    }
    new Stack()(manifest)
  }
}

此方法将生成适当的 list (来自 java 类)并将其显式传递给 Stack 构造函数。然后,您可以毫不费力地从 Java 使用它:

Stack<String> stack = Stack.ofType( String.class );
stack.push( "Hello" );
stack.push( "World" );

System.out.println( stack.size() );
System.out.println( stack.peek() ); 

关于java - 试图在 Java 中初始化 Scala 创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9860716/

相关文章:

使用 BCEL 的 Java 类修改顺序

java - 帮助我的 Android obj 加载器上的 UV

java - 服务和 DAO 总是实现接口(interface)

Scala 替代附加到列表的一系列 if 语句?

scala - 当processElement依赖于广播数据时,如何在flink中对BroadcastProcessFunction进行单元测试

scala - 如何查明我正在使用哪个 Play 版本?

java - 如何获取 Java 程序特定行的堆栈跟踪

java - 单个引用变量如何访问所有对象字段?

Java 解析 unicode 数学。 JSON 中的公式

java - 如何在 Intellij IDEA 中对 jar 文件进行签名?