0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is absolutely correct :) Calling it as the below works as well: fun String.removeNonAlphanumeric() = replace("[^a-ZA-Z0-9]".toRegex(), "")
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.