Kotlin extension method as an alias for a long method name?

I work in Kotlin, using Kotlin-native library object that contains the method .nameIsMuchTooLongAndIsStillNotClear. Similarly typealias, I want to create a method alias, so I can refer to it as .shortAndClear. To complicate the situation, these functions have several parameters, many of which have default values, which I would prefer not to pre-process in the wrapper. After further research, it still seems that the way is the way to go.

To use an example function that is easy to verify, let's say I want to create an alias extension for String.startsWithwhat is called String.beg. I can easily get the following solution to work:

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

However, it seems that this requires me to specify all the arguments and their default values, and do this for each overload. (The signatures of the actual methods in the question are significantly longer with many other defaults.) In the spirit of “don't repeat yourself,” is there a way I can use with, so I don’t have to list all the arguments? I tried several forms, but none of them work:

// none of these work:
fun String.beg = String::startsWith
fun String.beg = this::startsWith
val String.beg: (CharSequence, Boolean) -> Boolean = String::startsWith
+4
source share
1 answer

There is currently no way to fully accomplish what you are trying to do. If you want to keep your default settings, you need to do (as you said):

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 - .

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
+4

Source: https://habr.com/ru/post/1687111/


All Articles