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

后端 未结 4 1817
太阳男子
太阳男子 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:00

    I don't think this can be done easily with a for comprehension. But you could use partition.

    def getOffs(N:Int) = {
      val (evens, odds) =  0 until N partition { x => x % 2 == 0 } 
      evens foreach { x => println("skipping " + x) }
      odds
    }
    

    EDIT: To avoid printing the log messages after the partitioning is done, you can change the first line of the method like this:

    val (evens, odds) = (0 until N).view.partition { x => x % 2 == 0 }
    

提交回复
热议问题