简体   繁体   English

为 Scala 类创建一个空构造函数

[英]Make An Empty Constructor for Scala Class

If I have a case class like this:如果我有一个这样的案例类:

case class Foo(s : String, k : Int)

How do I specify an empty constructor for this?如何为此指定一个空的构造函数? The reason I need this is because I want to pass this class value to a Java API which requires that class has an empty constructor.我需要这个的原因是因为我想将这个类的值传递给一个 Java API,它要求该类有一个空的构造函数。 Do I specify default values for this?我是否为此指定默认值? I think I have to, I have no choice.我想我必须这样做,我别无选择。

You should be able to add a new constructor to the case class :您应该能够向case class添加一个新的构造函数:

case class Foo(s : String, k : Int) {
  def this() = this("default", 0)
}

val foo = new Foo()

Thanks to Mario Galic for checking that this does create the appropriate constructor in Java.感谢 Mario Galic 检查这是否在 Java 中创建了适当的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM