I am currently trying to extend Kotlins String class with a method in a file StringExt.kt
fun String.removeNonAlphanumeric(s: String) = s.replace([^a-ZA-Z0-9].Regex(), "")
But Kotlin in not allowing me to use this method in a lambda:
s.split("\\s ".Regex())
.map(String::removeNonAlphanumeric)
.toList()
The error is:
Required: (TypeVariable(T)) -> TypeVariable(R)
Found: KFunction2<String,String,String>
What confuses me about this is that Kotlins Strings.kt has very similar methods and I can call them by reference without Intellij raising this kind of issue. Any advice is appreciated.
CodePudding user response:
This is because you have declared an extension function that accepts an additional parameter and should be used as s.replace("abc")
.
I think what you meant is the following:
fun String.removeNonAlphanumeric(): String = this.replace("[^a-ZA-Z0-9]".toRegex(), "")
This declaration doesn't have an extra parameter and uses this
to refer to the String
instance it is called on.
CodePudding user response:
I thing this is because a lambda is an anonymous function and dose not access to the scope of a extension file.
Check this link maybe contains some useful information: https://kotlinlang.org/docs/reference/extensions.html