我试图与这个简单的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)
}
}
在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
另外,我没有得到任何输出到控制台!使用scala测试此代码可按预期工作。在这里发生了什么,我如何修复它以便clojure可以使用scala代码?
答案 0 :(得分:9)
在REPL中尝试这些:
(class b)
可能会告诉你它是indicators.DoubleRingBuffer
。
(vec (.getDeclaredMethods (class b)))
将为您提供类中声明的所有方法的向量,就像它是Java类一样,因此您可以看到它们的签名。
现在,使用这些方法名称和参数调用签名中显示的方法。
我有一种感觉,Scala正在处理方法参数的默认值。
编辑:正如评论中描述的那样,它不是。
如果这不起作用,您可以尝试将Scala字节码反编译为Java,以了解DoubleRingBuffer
类的外观。