Home > Blockchain >  Scala – Reduce, fold or scan (Left/Right) error cannot resolve symbol x
Scala – Reduce, fold or scan (Left/Right) error cannot resolve symbol x

Time:06-27

while performing a hands on code practice i am facing cannot resolve symbol x from intellj

error code line println(lst.reduceLeft((x,y) => {println(x " , " y) x y})) println(lst.reduceRight((x,y) => {println(x " , " y) x -y}))

i have tried to debugg from the suggestions from intellj but not working

Intellj Build #IC-221.5591.52, built on May 10, 2022

scala version scala-sdk-2.11.12

reference

http://www.codebind.com/scala/scala-reduce-fold-scan-leftright/?unapproved=192475&moderation-hash=8cdabb0f7834cbe19792b863eb952538#comment-192475

//In Scala Reduce, fold or scan are most commonly used with  collections in the form of reduceLeft, reduceRight, foldLeft, foldRight, scanLeft or scanRight.
// In general, all functions apply a binary operator to each element of a collection.
// The result of each step is passed on to the next step.

package pack {

}
object obj2 {

  println
  println("=====started=======")
  println

  //val is a constant (which is an un changeable variable),A variable holds a value / address to a value in memory
  val lst = List(1, 2, 3, 5, 7, 10, 13)

  val lst2 = List("A", "B", "C")


  def main(args: Array[String]) {

    println(lst.reduceLeft(_   _))


    println(lst2.reduceLeft(_   _))


    println(lst.reduceLeft((x,y) => {println(x   " , "  y) x  y}))

    println(lst.reduceLeft(_ - _))


    println(lst.reduceRight(_ - _))

    println(lst.reduceRight((x,y) => {println(x   " , "  y) x -y}))


    println(lst.foldLeft(100)(_   _))


    println(lst2.foldLeft("z")(_   _))


    println(lst.scanLeft(100)(_   _))


    println(lst2.scanLeft("z")(_   _))



  }
}

CodePudding user response:

println(lst.reduceLeft((x,y) => { println(x   " , "   y) x   y }))

The code inside the { } is not a valid expression. It looks like you are expecting Scala to work out that there are two expressions here, but it can't. You need to put in an explicit ; to fix it:

println(lst.reduceLeft((x,y) => { println(x   " , "   y); x   y }))

CodePudding user response:

println(lst.reduceLeft((x,y) => {println(x " , " y) x y})) is not valid. If you want several instructions in a anonymous function you need either to separate them with ; or make it multiline:

println(lst.reduceLeft((x, y) => { println(x   " , "   y); x   y }))

or

println(lst.reduceLeft((x, y) => {
  println(x   " , "   y)
  x   y
}))

Also better use string interpolation instead of concatenation:

println(lst.reduceLeft((x, y) => {
  println(s"$x , $y")
  x   y
}))
  • Related