java - 从 Java 实例化一个 Scala 类,并使用构造函数的默认参数

标签 java scala

我有一个Scala类:

class Foo(val x:String = "default X", val y:String = "default Y" ) 

我想从 Java 调用它,但使用默认参数

传递 null 不起作用(它分配 null,正如预期的那样)

new Foo(null,null); //both are instantiated as null

这个技巧对我有用,但它很丑,我想知道是否有更好的方法:

斯卡拉

class Foo(val x:String = "default X", val y:String = "default Y" ) {
  def this(x:Object) = this()
}

Java

new Foo(null); //no matter what I pass it should work

但是我想摆脱构造函数重载技巧,并使用 0 参数构造函数

这可能吗?

最佳答案

好像没有这个办法:https://issues.scala-lang.org/browse/SI-4278

Issue: default no-args constructor should be generated for classes with all-optional arguments
...

Lukas Rytz: in respect of language uniformity we decided not to fix this one - since it's a problem of interoperability with frameworks, we think it should not be fixed at the language level.

workarounds: repeat a default, or abstract over one, or put one default int the zero-argument constructor

然后 Lukas 提出了与您发现的相同的解决方案:

class C(a: A = aDefault, b: B = C.bDefault) {
  def this() { this(b = C.bDefault) }
}
object C { def bDefault = ... }

// OR

class C(a: A = aDefault, b: B) {
  def this() { this(b = bDefault) }
}

关于java - 从 Java 实例化一个 Scala 类,并使用构造函数的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059528/

相关文章:

java - 如何访问 XML 中的值

java - `name()` 与 `getName()` 命名约定?

scala - 在 Scala 中注释构造函数参数

scala - Scala中如何将DataFrame转换为RDD?

scala - Ubuntu下安装IntelliJ + Scala

scala - scala中调用map函数的不同方式

java - 警告 :The Jack toolchain is deprecated Android studio

java - pretty-print 。忽略空格

过滤器中的 Java OutOfMemory 错误

Scala 如何大写第一个字符和小写其他字符