Scala method and function examples

This page contains a collection of Scala method examples. I created many of these examples while I was writing the Scala Cookbook.

Unlike the Cookbook, where I explain these examples in great detail, on this page I’m just sharing many of the examples so you can use this as a method/function reference page. (The Cookbook contains more examples than this page, and explains them in detail.)

Declaring methods

You declare Scala methods with the def keyword, which is followed by the method name, method parameters, and the method body. These first three examples show different ways you can declare an add method, though the first approach is generally preferred for its simplicity:

// "normal" method definition
def add(a: Int, b: Int) = a + b

// same method, but with the return type declared
def add(a: Int, b: Int): Int = a + b

// define the method body in a block (in curly braces)
def add(a: Int, b: Int): Int = {
  a + b
}

When the body of a method is more than one line long, you need to define it as a block inside curly braces:

// put multiple lines in a block
def doSomeThings(x: Int, y: String, z: Pizza) = {
   doSomethingWithX(x)
   doSomethingWithY(y)
   doSomethingWithZ(z)
}

Public, private, protected

Methods are public by default, but you can also mark them as private or protected:

class Animal {
  private def heartBeat {} 
}

class Dog extends Animal {
  heartBeat  // won't compile
}

// marking a method protected makes the method available to subclasses
class Animal {
  protected def breathe {} 
}

class Dog extends Animal {
  breathe
}

Scala’s implementation of private is very flexible:

private[this]     method is only available to the current instance
private           method is available to the current instance and other instances of the same class
protected         method is only available to subclasses
private[model]    method is available to all classes beneath the com.acme.coolapp.model package
private[coolapp]  method is available to all classes beneath the com.acme.coolapp package
private[acme]     method is available to all classes beneath the com.acme package
(no modifier)     method is public

(Please see the Scala Cookbook for detailed descriptions of those examples.)

Calling methods in a superclass

You can call methods in a superclass:

class FourLeggedAnimal {
  def walk { println("I'm walking") }
  def run { println("I'm running") }
}

class Dog extends FourLeggedAnimal {
  def walkThenRun {
    super.walk
    super.run
  }
}

Setting default values for method parameters

You can set default values for method parameters:

class Connection {

  // default values specified here
  def makeConnection(timeout:Int = 5000, protocol:String = "http") {
      println("timeout = %d, protocol = %s".format(timeout, protocol))
      // more code here ...
  }
}

val c = new Connection
c.makeConnection()                 // timeout = 5000, protocol = http
c.makeConnection(2000)             // timeout = 2000, protocol = http
c.makeConnection(3000, "https")    // timeout = 3000, protocol = https

... this post is sponsored by my books ...
 

Using parameter names when calling a method

You can use parameter names when calling a method:

c.makeConnection(timeout = 10000, protocol = "https")   // specify the parameter names
c.makeConnection(protocol = "https", timeout = 10000)   // names can be in any order

Returning multiple items from a method

A method can return multiple items (a Tuple):

// a method that returns a tuple
def getStockInfo = {
  // other code here ...
  ("NFLX", 100.00, 101.00) // return a tuple
}

// call the method like this
val (symbol, currentPrice, bidPrice) = getStockInfo

// or call the method like this
val x = getStockInfo
x._1    // String = NFLX
x._2    // Double = 100.0
x._3    // Double = 101.0

Variable-argument (varargs) fields

Methods can have variable-argument (varargs) fields. Just add a * after the field definition:

def printAll(strings: String*) {
  strings.map(println)
}

// these all work
printAll()
printAll("foo")
printAll("foo", "bar")
printAll("foo", "bar", "baz")

Methods can throw exceptions

Methods can throw exceptions:

// can throw one exception
@throws(classOf[Exception])
override def play {
  // exception throwing code here ...
}

// can throw multiple exceptions
@throws(classOf[IOException])
@throws(classOf[LineUnavailableException])
@throws(classOf[UnsupportedAudioFileException])
def playSoundFileWithJavaAudio {
  // exception throwing code here ...
}

Summary

I hope these Scala method examples have been helpful. I’ll keep adding more examples here as I come up with them.