Duc
Duc

Reputation: 501

Initialize Scala variables with Option

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

Upvotes: 2

Views: 1450

Answers (3)

user908853
user908853

Reputation:

Since, the original_bar is always going to be initialized using bar's value, why not declare your case class as follows:

case class Foo(bar: String){
   val original_bar: Option[String] = Some(bar)
}

Also, if your bar is going to be changing, declare it as var:

case class Foo(var bar: String){
   val original_bar: Option[String] = Some(bar)
}

EDIT

This will do what you described in the comment:

Try this:

case class Foo(bar: String, original_bar: Option[String]) {
    def copy(bar1: String): Foo = Foo(bar1, this.original_bar)
}

val a = Foo("a",Some("a"))
a.bar // This gives 'a'
a.original_bar // This gives Some("a")

val b = a.copy("b")
b.bar // This gives 'b'
b.original_bar // This gives Some("a")

Upvotes: 1

Vladimir Matveev
Vladimir Matveev

Reputation: 128111

You can use multiple parameter lists:

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

This should work:

scala> case class Foo(bar: String)(val original_bar: Option[String] = Some(bar))
defined class Foo

scala> Foo("123")().original_bar
res79: Option[String] = Some(123)

This, however, interferes with case class functionality, for example, you won't be able to pattern match on second parameters list.

Upvotes: 3

vptheron
vptheron

Reputation: 7476

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))
}

Upvotes: 7

Related Questions