I am not able to execute
or **▶ button is not clickable in intelleiJ
** the sum function in following two ways. Please help me to identify the mistakes in both.
object Main{
def sum1(xs : List[Int]): Int = {
xs.filter(_ > 0).sum // am i missing return word here ?
}
def sum2(xs: List[Int]): Unit = {
val mx = xs.filter(_ > 0).sum // is it ok to have return in a variable ?
println(mx)
}
Main.sum1(List(1,2))
Main.sum2(List(1,2,3,4))
}
CodePudding user response:
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 code.
You can do this in 2 ways. Either define the main
method yourself, which is the conventional entry point to any application:
object Main {
def main(args: Array[String]): Unit = {
// your code here
}
}
Or - have your object extend the App
trait, which provides the main
method for you:
object Main extends App {
// your 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
It 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))
}