Home > Articles

This chapter is from the book

12.11 Nonlocal Returns

In Scala, you don’t use a return statement to return function values. The return value of a function is simply the value of the function body.

A return statement would be particularly problematic with control abstractions. For example, consider this function:

def indexOf(str: String, ch: Char): Int =
  var i = 0
  until (i == str.length) {
    if str(i) == ch then return i // No longer valid in Scala
    i += 1
  }
  -1

Does return return from the anonymous function { if str(i) == ch then return i; i += 1 } that is passed to until, or from the indexOf function? Here, we want the latter. Earlier versions of Scala had a return expression that threw an exception to the enclosing named function. That fragile mechanism has been replaced with the returning control abstraction:

import scala.util.control.NonLocalReturns.*

def indexOf(str: String, ch: Char): Int =
  returning {
    var i = 0
    until (i == str.length) {
      if str(i) == ch then throwReturn(i)
      i += 1
    }
    -1
  }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.