实际上,我是Kotlin的新手。因此,这个问题可能是非常基本的。
根据kotlin文档,可以将两个变量与===
和==
运算符进行比较。
第一个('==')检查它们是否具有相同的内容,第二个('+ ==')检查它们是否具有相同的引用。
但是,我找不到任何对象具有相同内容但具有不同引用的内置类。
var str1 : String = "Hello World"
var str2 : String = "Hello World"
if( str1 == str2 ){ // yes
print("Their contents are same\n")
{
if( str1 === str2 ){ // yes
print("Their references are same\n")
}
如果内容相同,我到目前为止遇到的所有类的实例都具有相同的引用。我们如何定义两个内容相同但引用不同的对象?
最佳答案
Referential equality is checked by the
===
operation (and its negated counterpart!==
).a === b
evaluates to true if and only if a and b point to the same object.
换句话说,
===
运算符比较a
和b
是否是相同的引用。在某些基本类型上进行测试可能会导致误导,原因是:一个例子是:
val a:Int? = 123
val b:Int? = 123
println(a === b) // => true
val c:Int? = 130
val d:Int? = 130
println(c === d) // => false
显然,在两种情况下,a==b
和c==d
为true。Since string interning is also possible at compile time在简单情况下,
===
也返回true
:val a = "ala"
val b = "ala"
println(a === b) // => true
val c = "!ala".substring(1)
val d = "!ala".substring(1)
println(c === d) // => false
Structural equalityStructural equality is checked by the
==
operation (and its negated counterpart!=
). By convention, an expression likea == b
is translated to:
a?.equals(b) ?: (b === null)
正如我们在上面看到的,对于
String
和Int
这样的内置类,即使它们的内容相等,对于引用相等===
返回false也是完全正常的。 Kotlin定义了一些类,这些类可以通过data classes
轻松地与内容进行比较,如下所示:数据类地址(val city:String,val street1:String)
val a = Address("Warsaw", "Jagielońska")
val b = Address("Warsaw", "Jagielońska")
println(a === b) // => false
println(a == b) // => true
关于kotlin - 引用和值(value)比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47989604/