在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”?因为我问的是与文档中的特定例子有关的疑问,而不仅仅是一般的疑问。


当前回答

在Kotlin中val是不可变的,var是可变的。

其他回答

在kotlin中,我们可以用两种类型声明变量:val和var。 Val不能重新赋值,它作为最终变量。

val x = 2
x=3 // cannot be reassigned

另一方面,var可以被重新赋值它是可变的

var x = 2
x=3 // can be reassigned

把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初始化。

在Kotlin中,我们有两种类型的变量:var或val 可在初始化后更新的可变引用(读写)。var 关键字用于定义Kotlin中的变量。它相当于一个普通的(非final) Java变量。如果我们的变量在某个时候需要改变,我们应该这样做 使用var关键字声明它。让我们看一个变量的例子 声明:

 fun main(args: Array<String>) {
     var fruit:String = "orange"  // 1
     fruit = "banana"             // 2
 }

和其他语言一样,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