Scala - can 'for-yield' clause yields nothing for some condition?

后端 未结 4 1778
太阳男子
太阳男子 2021-02-19 22:48

In Scala language, I want to write a function that yields odd numbers within a given range. The function prints some log when iterating even numbers. The first version of the fu

4条回答
  •  孤独总比滥情好
    2021-02-19 23:01

    I you want to keep the sequentiality of your traitement (processing odds and evens in order, not separately), you can use something like that (edited) :

    def IWantToDoSomethingSimilar(N: Int) =
      (for (n <- (0 until N)) yield {
        if (n % 2 == 1) {
            Option(n) 
        } else {
            println("skip even number " + n)
            None
        }
      // Flatten transforms the Seq[Option[Int]] into Seq[Int]
      }).flatten
    

    EDIT, following the same concept, a shorter solution :

    def IWantToDoSomethingSimilar(N: Int) = 
        (0 until N) map {
            case n if n % 2 == 0 => println("skip even number "+ n)
            case n => n
        } collect {case i:Int => i}
    

提交回复
热议问题