在 Kotlin 中一次定义多个变量(例如 Java : String x,y,z;) [英] Define multiple variables at once in Kotlin (e.g Java : String x,y,z;)
问题描述
我想知道是否有任何方法可以像 Java 和世界上几乎所有其他现有语言一样在 Kotlin 中同时定义多个变量.
I was wondering if there is any way to define multiple variables in Kotlin at once like in Java and almost every other existing language in the world .
就像在 Java 中一样:
like in Java :
String x = "Hello World!", y = null, z;
推荐答案
您可以声明(和分配)多个 变量在一行中使用分号 (;
):
You can declare (and assign) multiple variables in one line by using semicolons (;
):
val number = 42; val message = "Hello world!";
您还可以声明(和分配)多个属性 同样在同一行:
You can also declare (and assign) multiple properties in the same line similarly:
class Example {
var number = 42; var message = "Hello world!";
}
一个可运行的例子示出了两个见解,您可以在 tio.run 在线尝试(它在我使用 Kotlin 1.1.2-5 版(JRE 1.8)的本地环境中也运行良好.0_144-b01)):
A runnable example illustrating both insights that you can try online at tio.run (it also worked fine in my local environment using Kotlin version 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!
作为一个矛盾的旁注,在这个问题和答案,JetBrains 的工程师 yole 指出:
As a contradictory side note, in this question and answer, JetBrains' Engineer yole states that:
"在同一行上声明多个属性是不赞成的许多 Java 风格指南,所以我们没有实现对它的支持科特林."
"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 年了,所以从那时起可能会有变化.
Note that his answer is more than 4-years old, so there could have been changes since then.
这篇关于在 Kotlin 中一次定义多个变量(例如 Java : String x,y,z;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!