假设我有以下 Scala API,我计划从 Scala 和 Java 调用它:
sealed abstract class InterpMethod
case object InterpLinear extends InterpMethod
case object InterpNearest extends InterpMethod
case object InterpSpline extends InterpMethod
class Interpolator {
def interp(method: InterpMethod) = method match {
case InterpLinear => { ... }
case InterpNearest => { ... }
case InterpSpline => { ... }
}
}
object Interpolator { def apply() = new Interpolator }
// Scala Usage:
import myPackage._
Interpolator.interp(InterpNearest)
// Java Usage:
import myPackage.*
Interpolator myInterp = new Interpolator()
myInterp.interp(InterpNearest)
在 Scala 中运行良好。 Java抛出编译错误:InterpNearest无法解析为变量
有简单的解决方法吗?或者是一种对 Java 更友好的定义参数的更好方法?将参数定义为闭包会更好吗?
任何最佳实践或解决方法将不胜感激。这是一个更大的 fluent interface 的一部分。 。我的关键标准是它需要在 Java 和 Scala 中可用且干净。
最佳答案
http://lampwww.epfl.ch/~michelou/scala/using-scala-from-java.html说你可以像这样调用对象:
IterpNearest$.MODULE$
这不太好。我想你应该采纳@millimoose 的建议。
关于java - 针对 Java 兼容性的 Scala API 设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16339880/