Search code examples
androidkotlinstring-interpolation

How do I extend Kotlin string-interpolation to work with a custom class?


From what I have read in the documentation, it is my understanding that string interpolation in Kotlin works such that this code:

val n = 5 println("N is $n")

translates to

StringBuilder().append("N is ").append(n).toString()

which is fine and dandy for types for which Stringbuilder.append() has an implementation. I want now to use the Kotlin extension mechanic to be able to append my own class:

class Foo(a: Int = 0, b: Float = 0f) {} fun Stringbuilder.append(aFoo: Foo) : Stringbuilder! { return this.append("A = $a, B = $b") }

so that when I call:

aFoo = Foo(3,5.0f) println("aFoo parameters are: $aFoo")

it prints: "aFoo parameters are: A = 3, B = 5.0"

Unfortunately, it seems that my extension is shadowed by:

public open fun append(obj: Any!): StringBuilder!

I didn't manage to find in the documentation a way around this... Suggestions?

Thank you!


Solution

  • You could achieve that by overriding toString of Foo.

    class Foo(val a: Int = 0, val b: Float = 0f) {
    
        override fun toString(): String {
            return "A = $a, B = $b"
        }
    
    }