简体   繁体   English

使用可选参数从Java访问Scala的case类

[英]Access scala's case class from java with optional parameters

I have a case class having an optional parameter. 我有一个带有可选参数的case类。 When the parameter is not defined it should be set to some default. 如果未定义参数,则应将其设置为默认值。 Eg: 例如:

case class Foo(bar: Option[Int] = Some(100))

The problem arises when I try to access this case class from Java: 当我尝试从Java访问此case类时,就会出现问题:

Foo foo = new Foo(Option.empty())

It doesn't assign the default value 100 to variable bar 它不会将默认值100分配给变量bar

You can maybe use apply() method to get an instace of the class with default parameters in the following way: 您可以通过以下方式使用apply()方法获取具有默认参数的类的实例:

object Foo{
  def getDefault: Foo = new Foo
}

Which can be used like this in Java: 在Java中可以这样使用:

Foo.getDefault()

or if you have more than one default parameters then you will have to use the builder pattern like this: 或者,如果您有多个默认参数,则必须使用如下所示的构建器模式:

case class Foo(a: Int = 1, b: Option[Int] = None, c: String = "Hello")

object Foo{
  class Builder{
    var a = 1
    var b = None
    var c = "Hello"
    def withA(x: Int) = {a = x; this}
    def withB(x: Some) = {b = x; this}
    def withC(x: String) = {c = x; this}
    def build = Foo(a,b,c)
  }
}

You can do this: 你可以这样做:

case class Foo(bar: Option[Int]) {
  def this() = this(Some(100))
} 

If you run it in a scala worksheet with: 如果您在scala工作表中使用以下命令运行它:

object Foo{
  val a = new Foo()                         //> a  : week3.Foo = Foo(Some(100))
}

Hope this helps 希望这可以帮助

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

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