java - clojure/scala 互操作?

标签 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)
  }    
}

在 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 代码?

最佳答案

在 REPL 中尝试这些:

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

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

现在,使用这些方法名称和参数调用您在签名中看到的方法。

我感觉问题出在 Scala 处理方法参数默认值的过程中。

编辑:正如 OP 在评论中所描述的那样,事实并非如此。

如果这不起作用,您可以尝试将 Scala 字节码反编译为 Java,以了解 DoubleRingBuffer 是如何做到的。类看起来像。

关于java - clojure/scala 互操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4483091/

相关文章:

StringBuilder 的 Java Matcher.appendReplacement() 和 Matcher.appendTail()?

java - Android java.lang.RuntimeException : Error receiving broadcast Intent

scala - 列表中的前 n 个项目(包括重复项)

clojure - 在 clojure 函数名称中使用 - 和 *

clojure - 包括特定于平台的 java 依赖项(不让我的头发着火)

java - 应用程序在 Android Studio 中停止,但它可以编译

java - java中静态对象的返回值是线程安全的吗

clojure - 为什么 Clojure 的 loop 和 iterate 方法在速度上有如此大的差异

scala - IntelliJ 无法解析 Play 的 build.sbt libraryDependencies

scala mixin 和单一初始化