我是编程新手.最近,我开始学习Kotlin.

var  cont = "N"
var result:Int?
result = 45
println (cont + " + " + result)

It suggests converting this {" + "} to a template, but I do not know how?

推荐答案

在Kotlin中,可以使用字符串模板删除代码中的所有连接符号.他们总是从$开始.

例如,在您的代码中,您可以这样做:

println("$cont + $result")

This would print the same result as your original code, just more concise and readable. This can even be done on arbitrary expressions you just have to wrap it in curly braces.

例如:

val cont = "ALEC"
println("Hi ${cont.toLowerCase()}") //prints Hi alec

As mentioned in the comments, IntelliJ will do this automagically by hitting ALT + Enter when the hint is suggested.

Kotlin相关问答推荐

Jetpack Compose中的数字 Select 器问题

如何编写带有依赖项的自定义Kotlin串行化程序?

无法访问类kotlin.coroutines.CoroutineContext';.判断模块类路径中是否存在丢失或冲突的依赖项

如何修改muableStateMapOf的值?

始终抛出的函数 - 具有块主体的函数中需要的返回表达式

为什么这两个 Kotlin 协程函数不一样?

Kotlin 如何使用其 get 函数在内部检索映射值

根据字符串值动态过滤数组列表 - kotlin

如何在 Kotlin 中将with代码转换为完整代码?

Kotlin 使用委托进行隐式覆盖

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

Kotlin 从其他类调用成员扩展函数

jetpack compose 将参数传递给 viewModel

验证和 DDD - kotlin 数据类

如何在 Android Studio 3.1.3 中查看 Kotlin 中有趣的源代码?

Kotlin val difference getter override vs assignment

如何在特定条件下清除jetpack数据存储数据

Android Kotlin 创建类实现 Parcelable 在 writeToParcel 方法的 override中给出错误

Kotlin中的函数接口

Dagger 2 androidx fragment不兼容类型