For Intellij, unless you code from within a Scala Worksheet where you can execute execute code without an entry point, in any normal application, you require an entry point to your application.
In Scala 2 you can do this in 2 ways. Either define the main method yourself inside an object definition, which is the conventional way:
object Main {
def main(args: Array[String]): Unit = {
// code here
}
}
Or - have your object definition extend the App trait, which provides the main method for you, so you can start writing code directly inside:
object Main extends App {
// code here
}
This is a bit cleaner, and one nested-levels less.
In Scala, statements are called expressions, because they generally return the value of the last expression, if the last expression is not an assignment. This code:
def sum1(xs: List[Int]): Int =
xs.filter(_ > 0).sum
Is a syntactic sugar for this:
def sum1(xs: List[Int]): Int = {
return xs.filter(_ > 0).sum
}
Because braces are optional if the code has only 1 expression, and will return the value of the last expression by default. So even though you can write code both ways, you'll get the warning Return keyword is redundant, because you'll never need to use it explicitly.
Also, you don't need to write Main.sum1(...) from within Main. You can omit the object:
object Main extends App {
def sum1(xs: List[Int]): Int =
xs.filter(_ > 0).sum
def sum2(xs: List[Int]): Unit = {
val mx = xs.filter(_ > 0).sum
println(mx) // 10
}
println(sum1(List(1, 2))) // 3
sum2(List(1, 2, 3, 4))
}
For Scala 3, things get simpler. The recommended way is to annotate a method with the @main annotation to mark it as the entry point in your program. This method ca either be defined at the top-level, or inside an object definition, and it's name does not matter anymore:
@main def hello() =
// code here
While Scala 3 still supports the App trait from Scala 2, it has now become deprecated and it's functionality has been limited, so if your program needs to cross-build between both Scala 2 and Scala 3 versions, it’s recommended to stick with the basic way of explicitly define a main method inside an object definition with an Array[String] argument instead:
object MyMain:
def main(args: Array[String]) =
// code here
Note, curly braces become optional in Scala 3 in favor of the cleaner Python-style indentation.