varargs与单个参数

varargs与单个参数

本文介绍了Kotlin函数重载(varargs与单个参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数检查字符串是否为空.

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

因此,我尝试从第二个函数中调用第一个函数,但似乎它试图调用自身.例如,在Java中效果很好:

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

如何处理Kotlin中的这种情况?

How to handle such a situation in kotlin?

推荐答案

您可以使用函数引用,如下所示:

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

之所以可行,是因为 any 期望类型为(T) -> Boolean的参数,在这种情况下,TString.只有非vararg函数具有此类型,vararg函数的类型实际上是(Array<out String>) -> Boolean.

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.

这篇关于Kotlin函数重载(varargs与单个参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:37