https://kotlinlang.org logo
Title
l

lesincs

09/13/2021, 12:27 PM
How to write an internal extension function for an existing class? See thread.
if I have a
Foo
class, I can write an internal extension function for
String
, and I can use this extension function only in the
Foo
scope.
class Foo {
  fun String.greet(): String {
    return "Hello$this"
 }
}

fun main() {
  with(Foo()) {
    "str".greet()
 }
}
But what if the
Foo
class is in some library, how do I achieve the same functionality?
j

Javier

09/13/2021, 12:45 PM
context receivers is what you are looking for and they are not available
l

lesincs

09/13/2021, 12:51 PM
I see, thank you. Follow your information, I just found this reference: https://github.com/Kotlin/KEEP/issues/259
c

CLOVIS

09/16/2021, 5:08 PM
The closest thing you can have at the moment is to create a value class that wraps the class you don't control, and create an extension method there. However... I don't really think that will lead to nice code. Until context receivers are added, you're probably stuck with making it a normal method.
👍 1