How to get first 100 prime numbers in scala as i got result but it dispays blank where it's not found

后端 未结 3 1298
不思量自难忘°
不思量自难忘° 2021-01-28 18:14

output : prime numbers 2 3 () 5 () 7 () ()

i want as 2 3 5 7

def primeNumber(range: Int): Unit ={

    val primeNumbers: immutable.IndexedSeq[AnyVal] =
         


        
3条回答
  •  滥情空心
    2021-01-28 18:44

    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.

提交回复
热议问题