Table of Contents
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”.
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”:
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 arguments
To make your code clearer to the reader, you can use named arguments when calling functions:
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
I build softwares that solve problems. I also love writing/documenting things I learn/want to learn.