Roman Kosarev
Roman Kosarev

Reputation: 3

Scala best way to init several val from constructor value

i try to initialize several vals from constructor value

class lines(int value) {
   val line1 : String
   val line2 : String
   def this() {
      if (value >0) {
        line1="positive"
        line2="value"
      } else {
        line1 = "negative"
        line2 = "integer"
   }

I need to obtain and init several val's depends on constructor integer value. I know that i can use var instead of val or write two method for every val, but i want to find best scala way to solve this problem

Upvotes: 0

Views: 121

Answers (3)

alberto adami
alberto adami

Reputation: 749

I think that a valuable solution can be to use an if statement to valorize the vals directly in the Vals definition, without use the costructor.

class lines(int value) {
    val line1 : String = if(value > 0) "positive" else "negative"
    val line2 : String = if(value > 0) "value" else "integer"
 }

Upvotes: -1

Tim
Tim

Reputation: 27356

I would use pattern matching to implement multiple assignment:

class lines(value: Int) {
  val (line1, line2) =
    if (value > 0) {
      ("positive", "value")
    } else {
      ("negative", "integer")
    }
}

Upvotes: 3

Mario Galic
Mario Galic

Reputation: 48410

Try defining a factory in the companion object like so

final case class Lines(value: Int, line1: String, line2: String)

object Lines {
  def apply(value: Int): Lines = {
    if (value > 0)
      Lines(value, line1 = "positive", line2 = "value")
    else
      Lines(value, line1 = "negative", line2 = "integer")
  }
}

which gives

Lines(1)
res0: Lines = Lines(1,positive,value)

Lines(-1)
res1: Lines = Lines(-1,negative,integer)

Upvotes: 3

Related Questions