0

I have a question about setting the result to Empty (i.e. nothing), I've researched in past questions and did not find a good solution.

The question is quite simple, say I have a List of Int and List of Bool

val a = List(1,2,3,4,5)
val b = List(F,T,T,F,F)

and I want to zip them and do some mapping:

val result = (a,b).zipped.map((x,y)=>(if(b) a else ())

I assume I am doing the right thing above which takes each element of a and b and does the operation where if b is true, return a, else return nothing. I expect the result to only have the numbers (2,3). However, my Eclipse seems to indicate that the result generated is List[AnyVal] instead of List[Int].

I have tested the same setting, but using Lists, and when I set b to List(), the process works and Eclipse is understanding that I want to set an empty List, so I am lost where I when wrong..

Thanks in advance

3 Answers 3

3

You want val result = (a zip b).filter(_._2).map(_._1). map never filters, so don't attempt to return () from its argument and hope it will filter.

Sign up to request clarification or add additional context in comments.

Comments

1
val a = List(1, 2, 3, 4, 5)
val b = List(false, true, true, false, false)

a.zip(b)         // zip two lists
  .filter(_._2)  // filter if second element is true
  .map(_._1)     // grab first element of tuple

// List[Int] = List(2, 3)

Comments

0

You could also use collect, which will keep only the elements that match a pattern. You can think of it like a map that discards anything it's not defined for.

val a = List(1, 2, 3, 4, 5)
val b = List(false, true, true, false, false)

(a zip b) collect { case (x, true) => x }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.