在Kotlin中var和val的区别是什么?

我已经通过了这个链接:

属性和字段

如本连结所述:

只读属性声明的完整语法不同于 可变1有两种方式:它以val开头,而不是var 不允许设置。

但在此之前有一个使用setter的例子。

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

var和val的确切区别是什么?

为什么我们两者都需要?

这不是Kotlin中的变量的副本,与Java的区别:'var'和。“val”?因为我问的是与文档中的特定例子有关的疑问,而不仅仅是一般的疑问。


当前回答

把val比作final是错误的!

var是可变的,val是只读的;是的,val不能像Java中的final变量一样被重新赋值,但它们可以随着时间的推移返回不同的值,所以说它们是不可变的是错误的;

考虑以下几点

var a = 10
a = 11 //Works as expected
val b = 10
b = 11 //Cannot Reassign, as expected

到目前为止很好!

现在考虑以下关于val的情况

val d
  get() = System.currentTimeMillis()

println(d)
//Wait a millisecond
println(d) //Surprise!, the value of d will be different both times

因此,vars可以对应于Java中的非最终变量,但val也不是最终变量;

虽然kotlin中有类似final的const,因为它们是编译时常量,没有自定义getter,但它们只适用于原语

其他回答

如果我们使用val声明变量,那么它将是只读变量。我们不能改变它的值。它就像Java的最终变量。它是不可变的。

但如果我们使用var声明变量,那么它将是一个我们可以读或写的变量。我们可以改变它的值。这是可变的。

data class Name(val firstName: String, var lastName: String)

fun printName(name: Name): Name {
    val myName = Name("Avijit", "Karmakar") // myName variable is read only
    // firstName variable is read-only. 
    //You will get a compile time error. Val cannot be reassigned.
    myName.firstName = myName.firstName
    // lastName variable can be read and write as it's a var.
    myName.lastName = myName.lastName
    return myName
}

Val不能最近通过关键字lateinit初始化,但非原始变量可以最近通过关键字lateinit初始化。

和其他语言一样,Var也是一个变量。 如。

var price: Double

另一方面,val提供了引用功能。 如。

val CONTINENTS = 7
// You refer this to get constant value 7. In this case, val acts as access
// specifier final in Java

而且,

val Int.absolute: Int
    get() {
        return Math.abs(this)
    }
// You refer to the newly create 'method' which provides absolute value 
// of your integer

println(-5.absolute) // O.P: 5

两种方法创建变量在KOTLIN VAL和VAR

1.VAL存储常量值。也作Final Variable

2.VAR存储可变值

例如,点击这里

瓦尔: 必须添加或初始化值,但不能更改。 var: 它的变量可以在代码中的任何一行中更改。

Val (from value): 不可变的参考。用val声明的变量是不可以的 在初始化后重新赋值。它对应于Java中的最后一个变量。

Var (from variable): 可变参考。这样一个变量的值是可以改变的。 此声明对应于一个常规(非final) Java变量。