How does string interpolation work in Kotlin?

心已入冬 提交于 2019-12-20 10:36:10

问题


Does the Kotlin compiler translate "Hello, $name!" using something like

java.lang.String.format("Hello, %s!", name)

or is there some other mechanism?

And if I have a class like this for example:

class Client {
  val firstName: String
  val lastName: String
  val fullName: String
    get() = "$firstName $lastName"
}

Will this getter return a cached string or will it try to build a new string? Should I use lazyOf delegate instead?

I know that there will be no performance issue unless there will be millions of calls to fullName, but I haven't found documentation about this feature except for how to use it.


回答1:


The Kotlin compiler translates this code to:

new StringBuilder().append("Hello, ").append(name).append("!").toString()

There is no caching performed: every time you evaluate an expression containing a string template, the resulting string will be built again.




回答2:


Regarding your 2nd question: If you need caching for fullName, you may and should do it explicitly:

class Client {
    val firstName: String
    val lastName: String
    val fullName = "$firstName $lastName"
}

This code is equivalent to your snipped except that the underlying getter getFullName() now uses a final private field with the result of concatenation.




回答3:


As you know, in string interpolation, string literals containing placeholders are evaluated, yielding a result in which placeholders are replaced with their corresponding values. so interpolation (in KOTLIN) goes this way:

var age = 21

println("My Age Is: $age")

Remember: "$" sign is used for interpolation.




回答4:


You could do this:

String.format("%s %s", client.firstName, client.lastName)


来源:https://stackoverflow.com/questions/37442198/how-does-string-interpolation-work-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!