gpt4 book ai didi

variables - 在 Kotlin 中一次定义多个变量(例如 Java : String x, y,z;)

转载 作者:IT老高 更新时间:2023-10-28 13:28:03 35 4
gpt4 key购买 nike

我想知道是否有任何方法可以像在 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com