在Kotlin中,我试图动态创建一个文件名,其中包含一个类型和一个日期,如下所示:

var filename = "ab_$type_$date.dat"

However, the second underscore in between the variables is causing a compile error:

Kotlin: Unresolved reference: name_

我知道我可以用旧的方式连接字符串:

var filename = "ab_" + type + "_$date.dat"

But I'm wondering if there is a different way to accomplish the same thing. Is there a way to escape special characters in string templates or any other way to get this to work?

推荐答案

用大括号括起你的表情:

var filename = "ab_${type}_${date}.dat"

Kotlin相关问答推荐

如何在Kotlin中模拟www.example.com()?

等待下一个值时暂停Kotlin Coroutine

Kotlin中的增广赋值语句中的难以理解的错误

为什么可组合对象看似无状态(唯一传递的参数是函数,而不是状态),但会进行重组

Kotlin 说不需要强制转换,但删除后会出现新警告

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

为什么 trySend 会发出假数据?

如何在 kotlin 中使用带有泛型的密封类

Kotlin 列表扩展功能

Picasso 回调

如何使用 Kotlin KClass 属性 simpleName 生成空值

如何退出 Kotlinc 命令行编译器

将 jetpack compose 添加到现有元素

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

Kotlin中的下划线名称是为什么保留的?

Jetpack Compose 折叠工具栏

在android java类中使用Kotlin扩展

Kotlin flatMap - map

从另一个列表创建一个列表

项目不会使用 Kotlin 1.1.3 构建