Introduction

Conceptually, Scala methods are similar to Java methods in that they are behaviors you add to a class. However, they differ significantly in their implementation details. The following example shows some of the differences between Java and Scala when defining a simple method that takes an integer argument and returns a string:

// java
public String doSomething(int x) {
  // code here
}

// scala
def doSomething(x: Int): String = {
  // code here
}

This is just a start, though. Scala methods can be written even more concisely. This method takes an Int, adds 1 to it, and returns the resulting Int value:

def plusOne(i: Int) = i + 1

Notice that the return type didn’t have to be specified, and parentheses around the short method body aren’t required.

In addition to the differences shown in these simple examples, there are other differences between Java and Scala methods, including:

  • Specifying method access control (visibility)

  • The ability to set default values for method parameters

  • The ability to specify the names of method parameters when calling a method

  • How you declare the exceptions a method can throw

  • Using varargs fields in methods

This chapter demonstrates all of these method-related features.

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.