Scala functions

Defining a function in Scala is simple. Similar to other languages, to define a function you need to:

  • give it a name
  • declare parameters
  • specify the return types

A simple Scala function

Let’s create a function that accepts no parameters and doesn’t return anything:

  def sayHello(): Unit = println("Hello")

As you can see, this function accepts no parameter and all it does is print “Hello”.

Simple function that prints a message
A simple function that prints a message

Accepting parameters

The following function accepts a parameter type “Int”. All it does is print the string with the number value:

As you can see, I used “s” before the double quote to enable string interpolation.

  def printNumber(number: Int): Unit =
    println(s"Hello $number")

Calling this function with a number, says 3000, would print “Hello 3000”:

Calling function with parameters
Calling function with parameters

Specify return types

The following function specifies String as its return type:

  def goPicnic(isRaining: Boolean): String =
    if (isRaining) then "No way!" else "Let's go"

Default parameter values

You can specify a parameter’s default value so later, you can call the function without passing that parameter:

  def goToBed(isLate: Boolean = false): String =
    if (isLate) then "No way!" else "Let's go"

These calls are valid:

  def main(args: Array[String]): Unit = {
    goToBed()
    goToBed(true)
  }

Named parameters

To make your code clearer to the reader, you can use named parameters when calling the functions for more clarity:

  def main(args: Array[String]): Unit = {
    goToBed(isLate = true)
  }

Conclusion

In this post, you’ve learned how to create functions, declare parameters and specify return types in Scala.

The code for this post is available here on Github


Leave a Reply

Your email address will not be published.