Kotlinpoet: How do you MemberName with string temp...
# squarelibraries
h
Kotlinpoet: How do you MemberName with string templates? I want to use a member of an object:
println("Hello ${Foo.bar}")
but I get
println("Hello $Foo.bar")
which is wrong.
Copy code
import com.squareup.kotlinpoet.*

object Foo {
    val bar = "World"
}

val member = MemberName(ClassName("", "Foo"), "bar")

val function = FunSpec.builder("main")
function.addStatement("println(\"HELLO $%M\")", member)

function.build().toString()

// expected:
fun main() {
    println("HELLO ${Foo.bar}")
}
Do I have to add the brackets by myself? Or do you know some string template function?
p
Imo yes, just like you added the dollar sign
e
I like to do
Copy code
"""println("HELLO ${%M}")""".replace('$', '$')
to reduce the amount of escaping required
h
Okay, I already check if the member contains a enclosing class and add the brackets if needed.
e
it's safe to always add the brackets
kotlinpoet doesn't parse the expression so it doesn't know that it's inserting inside a string literal, but you do
h
Yeah, escaping the $ is annoying. Sure it is safe to add the brackets but I don't like them for "single" variables
e
also you would want to use
·
(which kotlinpoet replaces with space) to ensure that linewrapping doesn't happen in the middle of your string
also IIRC
Copy code
.addStatement("println(%P)", CodeBlock.of("HELLO \${%M}", member))
works to reduce the amount of quoting inside quoting
h
Wait, you can use \$? I didn't know this, nice! Yes, this was only a reproducer. My real code is quite complex and uses many code blocks
p
If you’re in triple quotes it gets a little more complicated and you’ll need:
Copy code
"""Hello ${'$'}"""
iirc 😛
h
"""Hello ${"$"}"""
this works too no need for the single quotes
but
"""Hello \$"""
is much nicer
e
that means something different
Copy code
"""Hello \$""" == "Hello \\\$" == "Hello " + '\\' + '$'
"Hello \$" == "Hello " + '$' == """Hello ${'$'}"""
h
Oh, you are right.
\$
only works with normal quotes, not with triple quotes. What a mess 😄
p
Actually it’s
Copy code
"""hello \$""" == ("hello " + "\\" + "$")
So
hello \$
Ah forget that, you already wrote that