Overloading the string template operator

I’m sure this has been answered somewhere, but is it possible to overload the string template operator?

For example, suppose I have the following code:

data class Point(val x: Int, val y: Int)
data class Stick(val p: Point, val q: Point)
console.log('${ Stick( Point(2,1) , Point(1,7) ) }')

The output is this:

Stick(p=Point(x=2, y=1), q=Point(x=1, y=7))

I’d prefer this:

[ ( 2 , 1 ) ; ( 1 , 7 ) ]

I could of course do this:

fun stick_string(s: Stick): String = "[ ( ${s.p.x} , ${s.p.y} ) ; ( ${s.q.x} , ${s.q.y} ) ] "
console.log("${stick_string( Stick( Point(2,1),Point(1,7) ) )}")

…but is it possible simply to overload the string template operator, so that I don’t have to do that?

Is there a reason you don’t want to override toString() method on your data class ?

If you’re searching for String templates à la scala, there’s a discussion going on here.

4 Likes

Is there a reason you don’t want to override toString() method on your data class ?

I wasn’t aware that that did what I wanted, but you’re right. Where is this documented? I looked at the page on operator overloading, at the page on string templates, and even (just now) at the page on toString(). None of them indicate a connection between $ and toString().

(To be clear, I’m sure it’s documented somewhere, because I have a vague memory of having read about this before, and possibly having done it before. I just can’t find it now, and it’s amazing how many online lessons on string templating go no further than how to use it.)

You’re right, this relation between $ (string templates) and toString doesn’t appear to be explicitly documented (as far as I could find).

The $ inside a string template are shorthand for concatenation, for example “foo $bar baz” can be written as “foo " + bar + " baz”, where the bar expression would be converted to a String via the Object.toString() method.

3 Likes