Shakti
Shakti

Reputation: 2033

In Scala how to ensure for comprehension iterates through all non empty lists?

I have the following two lists , I am not sure if at run time list2 will be empty or full , but list1 will be always non empty, how to ensure that for the following for loop value of list are at least printed

val list1 = List(1,2,3)                   //> list1  : List[Int] = List(1, 2, 3)
val list2 = List()                        //> list2  : List[Nothing] = List()
for( counti <- list1 ; countj <- list2 ) yield println (counti + " - " + countj)
                                                  //> res7: List[Unit] = List()

I am expecting something like

1 - BLANK
2 - BLANK
3 - BLANK

but above for loop is giving me blank results List()

Upvotes: 0

Views: 1177

Answers (2)

DaoWen
DaoWen

Reputation: 33029

First, you don't need yield if you're only using the for for side effects (printing):

for( counti <- list1 ; countj <- list2 )
  println (counti + " - " + countj)

Second, what do you expect the value of countj to be if you have an empty list? There's no way you can expect the code to work if there's no value for countj.

This might do what you want though:

// Just print counti
if (list2.isEmpty)
  for( counti <- list1 ) println(counti)
// Print both    
else for ( counti <- list1 ; countj <- list2 )
  println (counti + " - " + countj)

Upvotes: 2

dhg
dhg

Reputation: 52701

for (
  counti <- list1;
  countj <- if(list2.nonEmpty) list2 else List("BLANK")
) {
  println(counti + " - " + countj)
}

Upvotes: 6

Related Questions