Scala List.filter with two conditions, applied only once

前端 未结 4 366
旧时难觅i
旧时难觅i 2021-02-04 13:18

Don\'t know if this is possible, but I have some code like this:

val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
val evens = list.filter { e => e % 2 =         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 13:57

    You just write two conditions in the filter:

    val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
    
    var result = List(0)
    val someCondition = true
    
    result = if (someCondition) list.filter { e => e % 2 == 0 && e % 3 == 0 }
             else               list.filter { e => e % 2 == 0 && e % 5 == 0 }
    

提交回复
热议问题