Home > other >  Declaration never used - but it is?
Declaration never used - but it is?

Time:10-19

I am writing in scala and within this if statement I have a for loop and I initialized i=0 and used i in the for loop. it is telling me that declaration is not used but I am using it in the for loop. top is always equal to 5 also.

else {
    var i = 0
    for (i <- 0 until (top))

CodePudding user response:

For loops work a little different in Scala than other languages. In Scala, a for comprehension is syntax sugar over foreach, filter, map/flatMap higher order functions.

When you write

for (i <- 0 until top)

The compiler re-writes this to

(0 until top).foreach {
  i => ...
}

Here, the foreach body is an anonymous function where i is the function parameter that has the same type as the iterable. So you can just remove the declaration for i in your code snippet.

CodePudding user response:

Like posted before, the for in Scala is a very different animal than in e.g. Java. Using it as an iterator is only one of its many potential usages.
For your code: The first and the second i are not the same. In fact, the variable in the for expression is ephemeral and doesn't leave the for's scope, but actually shadows the outer one.

var i = 0 // you don't need this
for (i <- 0 until (top)) // loops from 0 to whatever top is regardless what's in the outer i

This will print 0 1 2 3 4:

val top = 5
for (i <- 0 until (top)) {
  println(i)
}

One really cool aspect of for comes from the yield keyword (example from the first link):

val names = List("adam", "david", "frank")
val ucNames = for (name <- names) yield name.capitalize

Also it is used to kind of map over multiple collections/monads etc. at once like in Haskell, a task rather tedious otherwise:

val names = List("adam", "david")
val numbers = List(1, 2)
val lst = for {
  name <- names
  number <- numbers
} yield s"$name: $number"

lst will now hold the cartesian product of the two lists as a List[String]: List("adam: 1", "adam: 2", "david: 1", "david: 2")

  • Related