1

I'm looking for a way to filter strings that end with one value from an array in Kotlin.

fun findStringsThatEndWith(sentences: List<String>, value: String) = sentences
    .filter { it.endsWith(value) }

This will allow me to filter all sentences that end with one value.

But what I would like to do is:

fun findStringsThatEndWith(sentences: List<String>, vararg value: String) = sentences
    .filter { it.endsWith(value // This won't work //) }

And when I do this, I will have to know how many values the vararg will hold.

fun findStringsThatEndWith(sentences: List<String>, vararg value: String) = sentences
    .filter { it.endsWith(value[0]) || it.endsWith(value[1]) }

1 Answer 1

4

In the lambda you pass to filter add a function that loops round the value parameter and checks each one, e.g.

fun findStringsThatEndWith(sentences: List<String>, vararg value: String) =
        sentences.filter { sentence -> value.any { sentence.endsWith(it) } }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.