Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Scala variables with Option

Tags:

scala

I have this scala case class:

case class Foo
    (bar: String,
     original_bar: Option[String] = None)

I would like to set original_bar = bar by default (so original_bar always = Some(bar) by default) such as:

case class Foo
        (bar: String,
         original_bar: Option[String] = Some(bar))

But I get: not found: value bar, I also tried Some(Foo.bar) but no luck. Is there a way to set default value within case class or I have to set it when I initialise Foo object? Thanks

like image 867
Duc Avatar asked Dec 13 '25 23:12

Duc


1 Answers

I don't think you can do that in the primary constructor. Here is an alternative:

case class Foo(bar: String, original_bar: Option[String])

object Foo {
  def apply(bar: String): Foo = new Foo(bar, Some(bar))
}
like image 192
vptheron Avatar answered Dec 15 '25 23:12

vptheron