since StringBuilder is an `expect class`, how woul...
# announcements
s
since StringBuilder is an
expect class
, how would one go about adding functionality to it? say I was a kotlin dev and wanted to add a new function, where would the actual implementation be? or if i wanted to modify the signature of an existing function by adding a new argument with a default value
a
You can define an extension function:
fun StringBuilder.myMethod()
: the implementation actually lives where the extension function is defined, i.e. equivalent to a Java static utility method. Extension functions are restricted to using the public API of the class they are defined as an extension on.
You can’t modify or override an existing method like this (easily), but you could add an overloaded version (e.g.
fun StringBuilder.toString(Charset)
that would sit alongside the existing class methods when resolving calls)
s
so that would probably be the best solution, even if i had the option of modifying the class itself?
a
That’s hard to answer, as it depends on the context. With StringBuilder, that isn’t a choice.
s
I see. Thanks.