title: When to use keyword return in Scala
body: <p>I learned early on that there is no reason to use the <code>return</code> keyword in Scala (as far as I'm aware). That being said I found an example where simply changing adding the <code>return</code> keyword made my function work, where it previously didn't.</p>
  <p>The code in question comes from <a href="https://github.com/ZachElkins/Advent-Of-Code-2020/tree/main/day07" rel="nofollow noreferrer">my solution</a> to the <a href="https://adventofcode.com" rel="nofollow noreferrer">Advent of Code</a> day 7 challenge.</p>
  <pre><code>
  def containsShinyGoldBag(bagContents: Map[String, List[String]], currentBag: String): Boolean = {
      val contents = bagContents(currentBag)
  
      if (bagContents(currentBag).contains(&quot;shiny gold&quot;) ) {
          // Base Case: Bag Found in list of bags
          true
      } else if (contents == List.empty){
          // Base Case: Dead End
          false
      } else {
          // Continue searching down list
  
          // Ideal solution ( gives same result as the working solution without return keyword )
          // for (b &lt;- contents) containsShinyGoldBag(bagContents, b)
  
          // Working solution
          for (b &lt;- contents) {
              if (containsShinyGoldBag(bagContents, b)) {
                  println(s&quot;Found one! $b inside a $currentBag&quot;)
                  return true // &lt;--- culprit
              }
              else false
          }
          false
      }
  }
  
  // In the main function
  
  var count = 0
  for (bag &lt;- bagContents.keys) {
      if (containsShinyGoldBag(bagContents, bag)) {
          count = count + 1
      }
  }
  println(s&quot;There are $count way to bring a shiny gold bag!&quot;)
  
  </code></pre>
  <p>When I run the code without <code>return</code> I end up with <code>count = 7</code>, which is the number of bags directly containing a shiny gold bag, rather than the correct number which counts bags that contain a shiny gold bag somewhere inside of one of their other bags down the line.</p>