跳到内容

%S 用于字符串

在生成包含字符串字面量的代码时,我们可以使用 %S 来生成一个字符串,它会自动添加引号并进行转义。这里有一个程序,它生成了 3 个方法,每个方法都返回自己的名称

fun main(args: Array<String>) {
  val helloWorld = TypeSpec.classBuilder("HelloWorld")
    .addFunction(whatsMyNameYo("slimShady"))
    .addFunction(whatsMyNameYo("eminem"))
    .addFunction(whatsMyNameYo("marshallMathers"))
    .build()

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

  kotlinFile.writeTo(System.out)
}

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

在这种情况下,使用 %S 会为我们添加引号

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

  fun eminem(): String = "eminem"

  fun marshallMathers(): String = "marshallMathers"
}