我想知道是否有任何方法可以像在 Java 和世界上几乎所有其他现有语言中一样在 Kotlin 中同时定义多个变量。
就像在 Java 中一样:
String x = "Hello World!", y = null, z;
最佳答案
您可以声明(和分配)多个 variables在一行中使用分号 (;
):
val number = 42; val message = "Hello world!";
您还可以声明(和分配)多个 properties同样在同一行:
class Example {
var number = 42; var message = "Hello world!";
}
一个可运行的示例,说明您可以try online at tio.run (它在我使用 Kotlin 版本 1.1.2-5 (JRE 1.8.0_144-b01) 的本地环境中也能正常工作):
class Example {
// declaring multiple properties in a single line
var number:Int; var message:String;
// constructor that modifies the parameters to emphasize the differences
constructor(_number:Int, _message:String) {
number = _number * 2
message = _message.toUpperCase()
}
}
fun main(args: Array<String>) {
// declaring multiple read-only variables in a single line
val number = 42; val message = "Hello world!";
// printing those local variables
println("[main].number = " + number)
println("[main].message = " + message)
// instantiating an object and printing its properties' values
val obj = Example(number,message)
println("[Example].number = " + obj.number)
println("[Example].message = " + obj.message)
}
执行输出:
[main].number = 42
[main].message = Hello world!
[Example].number = 84
[Example].message = HELLO WORLD!
作为一个矛盾的旁注,在 this question and answer , JetBrains 的工程师 yole声明:
"Declaring multiple properties on the same line is frowned upon by many Java style guides, so we did not implement support for that in Kotlin."
请注意,他的回答已经超过 4 年了,所以从那时起可能会有变化。
关于variables - 在 Kotlin 中一次定义多个变量(例如 Java : String x, y,z;),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385878/
相关文章:
java - Kotlin 泛型 Array
android - Kotlin:const val 与 val
java - 为什么以及何时将 @JvmStatic 与伴随对象一起使用?
gradle - 使用Gradle Kotlin DSL在Gradle中进行样板项目配置
gradle - 如何使用 kotlinscript DSL (build.gradle.kts)
constructor - Kotlin 数据类可以有多个构造函数吗?
android - 警告 "Kotlin plugin version is not the sam
android - RealmObject 的 Kotlin 数据类