我正在寻找一种方法来过滤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]) }
在传递给filter
的lambda中,添加一个函数,该函数围绕value
参数循环并检查每个参数,例如
fun findStringsThatEndWith(sentences: List<String>, vararg value: String) =
sentences.filter { sentence -> value.any { sentence.endsWith(it) } }