Kotlin function overloading (varargs vs single parameter)

和自甴很熟 提交于 2019-12-24 18:09:10

问题


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?


回答1:


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.




回答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?) }
}



回答3:


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() }


来源:https://stackoverflow.com/questions/49486877/kotlin-function-overloading-varargs-vs-single-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!