Kotlin扩展方法作为长方法名的别名?
问题描述:
我在Kotlin中使用Kotlin本机库对象,其中包含方法.nameIsMuchTooLongAndIsStillNotClear
。以类似于typealias
的方式,我想为该方法创建一个别名,所以我可以将其称为.shortAndClear
。稍微复杂一点,这些函数有几个参数,其中许多参数有默认值,我不希望在包装器中进行预处理。经过进一步的研究,它仍然像是一个extension function是要走的路。Kotlin扩展方法作为长方法名的别名?
要使用例如功能,很容易测试,让我们说,我想创建String.startsWith
一个别名型扩展被称为String.beg
。我可以很容易地得到以下解决方案的工作:
inline fun String.beg(prefix: CharSequence, ignoreCase: Boolean = false) = startsWith(prefix, ignoreCase) // works ok
然而,这似乎要求我列出所有参数及其默认值,并为每个超载这样做。 (真正的方法签名相当长,有更多的默认值。)本着“不要重复自己”的精神,是否有一种方法可以使用function reference至String::startsWith
,以便我不必枚举所有参数?我试过几种形式,但它们都没有工作:
// none of these work:
fun String.beg = String::startsWith
fun String.beg = this::startsWith
val String.beg: (CharSequence, Boolean) -> Boolean = String::startsWith
答
目前没有办法完全达到你正在尝试做的。如果你想保持你的默认参数,你必须做的(如你所说):
fun String.beg(prefix: CharSequence, ignoreCase: Boolean = false) = startsWith(prefix, ignoreCase)
// Or if you know that ignoreCase will be always false, you can pass the value directly to "startsWith()
fun String.beg(prefix: CharSequence) = startsWith(prefix, false)
相反,如果你还没有缺省参数,或者如果你有传递时的默认值,你不在乎你会调用这个函数,你可以使用一个函数引用。
val String.beg: (CharSequence, Boolean) -> Boolean get() = this::startsWith
// If the parameters can be inferred, you can avoid the type specification.
// In this case it won't compile because there are several combinations for "startsWith()".
val String.beg get() = this::startsWith
在这种情况下,因为beg
是一个lambda你不能指定参数的默认值。
由于Kotlin 1.2(目前处于测试阶段),您可以避免在函数引用上指定this
。同样的例子写在上面,但在Kotlin 1.2中:
val String.beg: (CharSequence, Boolean) -> Boolean get() = ::startsWith
// If the parameters can be inferred, you can avoid the type specification.
// In this case it won't compile because there are several combinations for "startsWith()".
val String.beg get() = ::startsWith