How to write an internal extension function for an...
# getting-started
l
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.
Copy code
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
context receivers is what you are looking for and they are not available
l
I see, thank you. Follow your information, I just found this reference: https://github.com/Kotlin/KEEP/issues/259
c
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