Last Updated: February 05, 2021
·
1.102K
· daverstevens

You can use unapply methods outside of match statements

I notice that many scala developers don't realize that you can make use of unapply anywhere in your code.

Take some function which returns a tuple

scala> def foo = (1, 2)
foo: (Int, Int)

You can extract the values with tuples unapply operator

scala> val (l, r) = foo
l: Int = 1
r: Int = 2

Here's another example with case classes

scala> case class Bar(l: Int, r: Int)
defined class Bar

scala> val bar = Bar(4, 5)
bar: Bar = Bar(4,5)

scala> var Bar(leftValue, rightValue) = bar
leftValue: Int = 4
rightValue: Int = 5