字符串插值在Kotlin中如何工作? [英] How does string interpolation work in Kotlin?
问题描述
Kotlin编译器是否使用类似的方式翻译"Hello, $name!"
Does the Kotlin compiler translate "Hello, $name!"
using something like
java.lang.String.format("Hello, %s!", name)
还是还有其他机制?
例如,如果我有一个像这样的课程:
And if I have a class like this for example:
class Client {
val firstName: String
val lastName: String
val fullName: String
get() = "$firstName $lastName"
}
此getter会返回缓存的字符串还是会尝试构建新的字符串?我应该改用lazyOf委托吗?
Will this getter return a cached string or will it try to build a new string? Should I use lazyOf delegate instead?
我知道除非有成千上万的fullName
调用,否则不会有性能问题,但是除了如何使用它之外,我还没有找到有关此功能的文档.
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.
推荐答案
Kotlin编译器将此代码转换为:
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.
这篇关于字符串插值在Kotlin中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!