Venkat Dabri
Venkat Dabri

Reputation: 41

using the object in the match clause of pattern match in Scala

I have code like this:

val s = someOtherObject.subObjects().size match {
  case size > 0 => "Size is greater than 0"
  case _ => "Size is less than 0"
}

How do I assign the value of someOtherObject.subObjects().size in the match clause to the size variable in the case statement

Do I have to do :

val size = someOtherObject.subObjects().size
val s = size match {
  case size > 0 => "Size is greater than 0"
  case _ => "Size is less than 0"
}

Upvotes: 1

Views: 99

Answers (2)

Amoo Hesam
Amoo Hesam

Reputation: 480

You can give that variable a name and return it back like this:

val s = someOtherObject.subObjects().size match {
  case size if size > 0 => size
  case size @ _ => size
}

Or you can simply use if expressions:

val size = someOtherObject.subObjects().size

val result = if(size > 0) {
  // Size is greater than zero
  size
} else {
  // Size is less than or equal to zero
  size
}

Upvotes: 0

Abhi
Abhi

Reputation: 366

val s = size match {
  case x if x > 0 => ("Size is greater than 0", x)
  case x @ _ => ("Size is less than 0", x)
}

s will be tuple (String, Int)

s._1 will be string message

s._2 will be value of size.

Upvotes: 2

Related Questions