Kotlin扩展方法作为长方法名的别名?

我在Kotlin中使用一个Kotlin本地库对象,其中包含一个方法,它的.nameIsMuchTooLongAndIsStillNotClear 。 以类似于typealias的方式,我想创建一个方法的别名,所以我可以把它称为.shortAndClear 。 稍微复杂的事情,这些函数有几个参数,其中许多默认情况下,我不希望在包装预处理。 经过进一步的研究,它似乎仍然是一个扩展功能的路要走。

要使用一个容易测试的示例函数 ,假设我想为String.startsWith创建一个名为String.beg的别名类型的扩展。 我可以很容易地得到以下解决方案的工作:

 inline fun String.beg(prefix: CharSequence, ignoreCase: Boolean = false) = startsWith(prefix, ignoreCase) // works ok 

但是,这似乎要求我列出所有的参数和它们的默认值,并为每个重载。 (真正的方法签名是相当长的更多的默认值。)本着“不要重复自己”的精神,是否有一种方法,我可以使用一个函数引用 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