Functions: Toplevel Functions (Scala 3 Video)
Scala 3 supports toplevel functions, which are functions that are not contained inside a class, trait, or object.
Conversely, in Scala 2, all functions and methods must be inside one of those containers (class, trait, or object).
In Scala 3, values can also be at the top level of your code.
I have seen “toplevel” spelled as toplevel, top level, and top-level.
Toplevel function example
Here’s an example of two toplevel functions in a small Scala script:
// toplevel function
def sayHello(name: String): Unit =
println(s"Hello, $name")
// toplevel function
def containsSubstringIgnoreCase(s: String, substring: String): Boolean =
s.toUpperCase.contains(substring.toUpperCase)
// toplevel value
val lookFor = "al"
@main def helloWorld(name: String): Unit =
sayHello(name)
if containsSubstringIgnoreCase(name, lookFor) then
println(s"Congratulations, your name contains '$lookFor'!")
else
println(s"Sorry, your name doesn’t contain '$lookFor'.")
As shown, functions are now free to be outside of containers, which is nice in some situations, such as scripts and small applications.
Update: All of my new videos are now on
LearnScala.dev