Fixing scala error: “error: return outside method definition”

If you are starting at Scala, and are accustomed to older languages, you may be tempted to sort a list like so:

val x = new List(3, 1, 2)
 
x.sortWith( 
  (a, b) => { 
    return a > b
  } 
)

This code will throw the following error:

error: return outside method definition

The intent of this code is to create the equivalent of a Java comparator, using an anonymous function. However, “return” is not defined correctly in Scala, and should never be used.

The above example can be rewritten like so:

val x = new List(3, 1, 2)
 
x.sortWith( 
  (a, b) => { 
    a > b
  } 
)

This implicitly returns a value from the function. The “return” keyword returns from a function that is tied to an object (a “method”), so if this code was inside a method it would “work”, but drop several stack frames.

Leave a Reply

Your email address will not be published. Required fields are marked *