output : prime numbers 2 3 () 5 () 7 () ()
i want as 2 3 5 7
def primeNumber(range: Int): Unit ={
val primeNumbers: immutable.IndexedSeq[AnyVal] =
so the underlying problem here is that your yield
block effectively will return an Int
or a Unit
depending on isPrime
this leads your collection to be of type AnyVal
because that's pretty much the least upper bound that can represent both types. Unit
is a type only inhabited by one value which is represented as an empty set of round brackets in scala ()
so that's what you see in your list.
As Puneeth Reddy V said you can use collect
to filter out all the non-Int values but I think that is a suboptimal approach (partial functions are often considered a code-smell depending on what type of scala-style you do). More idiomatic would be to rethink your loop (such for loops are scarcely used in scala) and this could be definitely be done using a foldLeft
operation maybe even something else.