我正在寻找一种方法来过滤Kotlin数组中以一个值结尾的字符串。
fun findStringsThatEndWith(sentences: List<String>, value: String) = sentences
.filter { it.endsWith(value) }
这将允许我过滤所有以一个值结尾的句子。
但是我想做的是:
fun findStringsThatEndWith(sentences: List<String>, vararg value: String) = sentences
.filter { it.endsWith(value // This won't work //) }
当我这样做时,我将不得不知道vararg将保留多少个值。
fun findStringsThatEndWith(sentences: List<String>, vararg value: String) = sentences
.filter { it.endsWith(value[0]) || it.endsWith(value[1]) }
答案 0 :(得分:4)
在lambda中,您传递给filter
,该函数会循环value
参数并检查每个参数,例如
fun findStringsThatEndWith(sentences: List<String>, vararg value: String) =
sentences.filter { sentence -> value.any { sentence.endsWith(it) } }