Skip to content

%S for Strings

When emitting code that includes string literals, we can use %S to emit a string, complete with wrapping quotation marks and escaping. Here’s a program that emits 3 methods, each of which returns its own name:

fun main(args: Array<String>) {
  val helloWorld = TypeSpec.classBuilder("HelloWorld")

  val kotlinFile = FileSpec.builder("com.example.helloworld", "HelloWorld")


private fun whatsMyNameYo(name: String): FunSpec {
  return FunSpec.builder(name)
    .addStatement("return %S", name)

In this case, using %S gives us quotation marks:

class HelloWorld {
  fun slimShady(): String = "slimShady"

  fun eminem(): String = "eminem"

  fun marshallMathers(): String = "marshallMathers"