Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala case classes and tail recursion best practices

I'm fairly new to scala from java and also pretty new to pattern matching. One of the things I'm trying to get my head around is when to use it and what it's costs/benefits are. For example this

def myThing(a: Int): Int = a match {
  case a: Int if a > 0 => a
  case _ => myThing(a + 1)
}

Does the same thing as this (unless I've really misunderstood something)

def myThing(a: Int): Int = {
  if (a > 0) a
  else myThing(a + 1)
}

So my actual question: But do they run the same way? Is my pattern matched example tail recursive? And if not, then why not when it is in the second example?

Are there any other things I should worry about, like resources? Or should I pretty much always try to use pattern matching?

I've searched around for these answers but haven't found any "best practices" for this!

Edit: I'm aware that the example used is a bit contrived - I've just added it to be clear about the question below it - thanks!

like image 374
Hamish Avatar asked Feb 10 '26 22:02

Hamish


1 Answers

Yes they do run the same. Best practice for every syntactic sugar is the same: use it whenever it provides more readable or flexible code. In your examples in case of if statement you may omit braces and write just

def myThing(a: Int): Int =  if (a > 0) a else myThing(a + 1)

Which is definitely more handy than pattern matching. Pattern matching is handy in situations where:

  • You have 3 or more alternatives
  • You should unpack\check values through extractors (check this question)
  • You should check the types

Also to ensure you function is tail-recursive you could use the @tailrec annotation

like image 72
Odomontois Avatar answered Feb 12 '26 11:02

Odomontois



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!