clojure/scala interop?

jos*_*osh 6 java scala clojure

我试图插入这个简单的scala代码,但我遇到了一些麻烦.

package indicators

class DoubleRingBuffer(val capacity:Int=1000) {
  var elements = new Array[Double](capacity);
  private var head=capacity-1
  private var max=0

  def size ():Int = {
    return max+1
  }

  def add(obj:Double):Double = {
    head-=1
    if (head<0) head=capacity-1
    return set(max+1,obj)
  }

  def set(i:Int,obj:Double):Double = {
    System.out.println("HI")
    if (i>=capacity || i<0)
      throw new IndexOutOfBoundsException(i+" out of bounds")
    if (i>=max) max=i
    var index = (head+i)%capacity
    var prev = elements(index)
    elements(index)=obj
    return prev
  }

  def get(i:Int=0):Double = {
    System.out.println("size is "+size())
    if (i>=size() || i<0)
      throw new IndexOutOfBoundsException(i+" out of bounds")
    var index = (head+i)%capacity
    return elements(index)
  }    
}
Run Code Online (Sandbox Code Playgroud)

在clojure中,我这样做

(import 'indicators.DoubleRingBuffer)
(def b (DoubleRingBuffer. 100))
(pr (.size b)) ;;ERROR: No matching field found: size for class indicators.DoubleRingBuffer
(pr (.get b 33)) ;;returns 0: should throw an index out of bounds error!
(pr (.get b 100)) ;;throws index out of bounds error, as it should
Run Code Online (Sandbox Code Playgroud)

另外,我没有得到任何输出到控制台!使用scala测试此代码可按预期工作.什么事情发生在这里,我如何解决它,以便clojure可以使用scala代码?

Gor*_*vic 9

在REPL中尝试这些:

(class b)可能会告诉你的indicators.DoubleRingBuffer.

(vec (.getDeclaredMethods (class b))) 将为您提供在您的类中声明的所有方法的向量,就好像它是一个Java类,因此您可以看到它们的签名.

现在,使用这些方法名称和参数调用签名中显示的方法.

我有一种感觉,问题出在Scala处理方法参数的默认值.

编辑:作为评论中描述的OP,它不是.

如果这不起作用,您可以尝试将Scala字节码反编译为Java,以了解DoubleRingBuffer类的外观.