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


当前回答

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

其他回答

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

val变量的值只能赋值一次。

val address = Address("Bangalore","India")
address = Address("Delhi","India") // Error, Reassigning is not possible with val

虽然你不能重新赋值,但你可以修改对象的属性。

//Given that city and country are not val
address.setCity("Delhi") 
address.setCountry("India")

这意味着您不能更改变量所指向的对象引用,但可以更改该变量的底层属性。

可以根据需要多次重新分配var变量的值。

var address = Address("Bangalore","India")
address = Address("Delhi","India") // No Error , Reassigning possible.

显然,它的底层属性可以被改变,只要它们没有被声明为val。

//Given that city and country are not val
address.setCity("Delhi")
address.setCountry("India")

简单地说, var(可变的)和val(在Java中不可变的值(最终修饰符))

var x:Int=3
x *= x

//gives compilation error (val cannot be re-assigned)
val y: Int = 6
y*=y

如果我们使用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存储任何对象,它可能会随着时间而改变。

例如:

fun main(args: Array<String>) {
    var a=12
    var b=13
    var c=12
    a=c+b **//new object 25**
    print(a)
}

Val的意思是值,它就像java中的“常量”。如果你使用Val存储任何对象,它就不能及时改变。

例如:

fun main(args: Array<String>) {
    val a=12
    var b=13
    var c=12
    a=c+b **//You can't assign like that.it's an error.**
    print(a)
}