在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存储任何对象,它可能会随着时间而改变。

例如:

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)
}

如果我们使用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初始化。

+----------------+-----------------------------+---------------------------+
|                |             val             |            var            |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable(once initialized  | Mutable(can able to change|
|                | can't be reassigned)        | value)                    |
+----------------+-----------------------------+---------------------------+
| Example        | val n = 20                  | var n = 20                |
+----------------+-----------------------------+---------------------------+
| In Java        | final int n = 20;           | int n = 20;               |
+----------------+-----------------------------+---------------------------+

参考

我们使用var来声明变量和 我们使用val来创建在Java中前面带有保留字final的常量

基本上

Var =变量,所以它可以改变 Val = value,所以它不能改变。