1

I have two functions check if String/Strings are blank.

fun isBlank(s: String?) : Boolean {
            return s.isNullOrBlank()
        }

fun isBlank(vararg strings: String) : Boolean {
            return strings.isEmpty() ||
                    strings.any { isBlank(it) }
        }

So I try to call first function from the second one but seems it tries to call itself. For instance it works nice in java:

public static boolean isBlank(final String string) {
        return string == null || string.trim().isEmpty();
}

public static boolean isBlank(final String... strings) {
        return strings.length == 0
                || Arrays.stream(strings).anyMatch(StringUtil::isBlank);
}

How to handle such a situation in kotlin?

3 Answers 3

6

You can do the same thing as in Java with a function reference, which would look like this:

fun isBlank(vararg strings: String) : Boolean {
    return strings.isEmpty() || strings.any(::isBlank)
}

This works because any expects a parameter of type (T) -> Boolean, T in this case being String. Only the non-vararg function has this type, the vararg function's type is actually (Array<out String>) -> Boolean.

Sign up to request clarification or add additional context in comments.

2 Comments

Why does that call the "correct" overload to be called?
I've added explanation to my answer.
2

There's a little problem, I guess: The vararg function can not be called with null currently, you only accept String. Checking for null doesn't make sense anyway. You would have to change the parameter strings to type vararg strings: String?. Another solution is casting to String? inside any:

fun isBlank(vararg strings: String): Boolean {
    return strings.isEmpty() ||
            strings.any { isBlank(it as String?) }
}

Comments

0

The second function calls itself because the type of it (in strings.any { isBlank(it) }) is String, which is the type this second function accepts. The compiler chooses this function because, though the first one also accepts String, it receives String?.

Anyway, you could have just this function:

fun isBlank(vararg strings: String?)
        = strings.any { it == null || it.isEmpty() || it.isBlank() }

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.