0

I have writtent following code to check if string contains any of of the words.

fun String.isValidUrl(): Boolean {
    return contains("http://") || contains("https://") || contains("www.")
}

How can I simplify this statement in kotlin.

1 Answer 1

3

In this case, you may want to use startsWith() rather than contains(). Or it might not detect invalid URLs like, say, abc://www.example.com

You can use this:

val prefixes = arrayOf("http://", "https://", "www.")

fun String.isValidUrl() = prefixes.any { this.startsWith(it) }

OR

Use Android's built-in URLUtil.isValidUrl()

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.