When is a return type required for methods in Scala?

The Scala compiler can often infer return types for methods, but there are some circumstances where it's required to specify the return type. Recursive methods, for example, require a return type to be specified.

I notice that sometimes I get the error message "overloaded method (methodname) requires return type", but it's not a general rule that return types must always be specified for overloaded methods (I have examples where I don't get this error).

When exactly is it required to specify a return type, for methods in general and specifically for overloaded methods?

Answers


The Chapter 2. Type Less, Do More of the Programming Scala book mentions:

When Explicit Type Annotations Are Required.

In practical terms, you have to provide explicit type annotations for the following situations:

Method return values in the following cases:

  • When you explicitly call return in a method (even at the end).
  • When a method is recursive.
  • When a method is overloaded and one of the methods calls another. The calling method needs a return type annotation.
  • When the inferred return type would be more general than you intended, e.g., Any.

Example:

// code-examples/TypeLessDoMore/method-nested-return-script.scala
// ERROR: Won't compile until you put a String return type on upCase.

def upCase(s: String) = {
  if (s.length == 0)
    return s    // ERROR - forces return type of upCase to be declared.
  else
    s.toUpperCase()
}

Overloaded methods can sometimes require an explicit return type. When one such method calls another, we have to add a return type to the one doing the calling, as in this example.

// code-examples/TypeLessDoMore/method-overloaded-return-script.scala
// Version 1 of "StringUtil" (with a compilation error).
// ERROR: Won't compile: needs a String return type on the second "joiner".

object StringUtil {
  def joiner(strings: List[String], separator: String): String =
    strings.mkString(separator)

  def joiner(strings: List[String]) = joiner(strings, " ")   // ERROR
}
import StringUtil._  // Import the joiner methods.

println( joiner(List("Programming", "Scala")) )

The two joiner methods concatenate a List of strings together. The first method also takes an argument for the separator string. The second method calls the first with a “default” separator of a single space.

If you run this script, you get the following error.

... 9: error: overloaded method joiner needs result type
def joiner(strings: List[String]) = joiner(strings, "")

Since the second joiner method calls the first, it requires an explicit String return type. It should look like this:

def joiner(strings: List[String]): String = joiner(strings, " ")

Basically, specifying the return type can be a good practice even though Scala can infer it.


Randall Schulz comments:

As a matter of (my personal) style, I give explicit return types for all but the most simple methods (basically, one-liners with no conditional logic).

Keep in mind that if you let the compiler infer a method's result type, it may well be more specific than you want. (E.g., HashMap instead of Map.)

And since you may want to expose the minimal interface in your return type (see for instance this SO question), this kind of inference might get in the way.


And about the last scenario ("When the inferred return type would be more general than you intended"), Ken Bloom adds:

specify the return type when you want the compiler to verify that code in the function returns the type you expected

(The faulty code which triggers a "more general than expected return type was:

// code-examples/TypeLessDoMore/method-broad-inference-return-script.scala
// ERROR: Won't compile. Method actually returns List[Any], which is too "broad".

def makeList(strings: String*) = {
  if (strings.length == 0)
    List(0)  // #1
  else
    strings.toList
}

val list: List[String] = makeList()  // ERROR

, which I incorrectly interpreted and List[Any] because returning an empty List, but Ken called it out:

List(0) doesn't create a list with 0 elements. It creates a List[Int] containing one element (the value 0). Thus a List[Int] on one conditional branch and a List[String] on the other conditional branch generalize to List[Any]. In this case, the typer isn't being overly-general -- it's a bug in the code. )


Need Your Help

OR clause in firebase java android

java android firebase where

Does anyone know how I can do a common "OR" like in a where clause, in firebase?

git pull, keep untracked files ignore and overwrite tracked file modified or deleted

git production pull

I would like to do a git pull to the production server but I'm having some issues.