As part of my learning, I am trying to write the Scala expression into a scala script but struck with an error.
The scala code I am having it successfully executed in Scala REPL is
def intList = List[1,2,3,4,5]
intList.filter(x => x%2 ==1).map(x => x * x).reduce((x,y) => x+y)
This successfully gets executed and the following is the result I get.
scala> intList.filter(x => x % 2 == 1).map(x => x * x).reduce((x,y) => x + y)
res15: Int = 35
I am trying to make this as a Scala script or class so as to rerun any number of times on demand. I save this in a file named SumOfSquaresOfOdd.scala
import scala.collection.immutable.List
object SumOfSquaresOfOdd extends App
{
def main(args:Array[String]):Unit =
{
var intList = List[Integer](1,2,3,4,5,6,7,8,9,10)
def sum = intList.filter(x => x % 2 ==1).map(x => x * x).reduce((x+y) => x + y)
println sum
}
}
When I compile this using scalac, the following error is printed on the console.
λ scalac SumOfSquaresOfOdd.scala
SumOfSquaresOfOdd.scala:8: error: not a legal formal parameter.
Note: Tuples cannot be directly destructured in method or function parameters.
Either create a single parameter accepting the Tuple1,
or consider a pattern matching anonymous function: `{ case (param1, param1) => ... }
def sum = intList.reduce(x => x % 2 ==1).map(x => x * x).reduce((x+y) => x + y)
^
one error found
How do I use the filter, map, reduce methods in a script? Appreciate your help and support.
UPDATE: Typos updated in the code.