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

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

    def IWantToDoSomethingSimilar(N: Int) = 
      for {
        n <- 0 until N
        if n % 2 != 0 || { println("skip even number " + n); false }
      } yield n
    

    Using filter instead of a for expression would be slightly simpler though.

提交回复
热议问题