给出以下代码:
val value = "something"
println(value.toUpperCase().toLowerCase() == value) // prints true
println(value.toUpperCase().toLowerCase() === value) // prints false
Run Code Online (Sandbox Code Playgroud)
在Kotlin / JVM 1.3.40上,我得到:
true
false
Run Code Online (Sandbox Code Playgroud)
在Kotlin / JS 1.3.40上,我得到:
true
true
Run Code Online (Sandbox Code Playgroud)
我希望两者都能得到相同的结果,并且我希望整体获得Kotlin / JVM的结果(因为我应该有不同的String对象)。
为什么根据运行时环境获得不同的结果?
这是因为运行时处理它的方式。
在 JVM 上,==映射到equals,并===映射到==(身份检查),如此处所述。同时,JavaScript 的equals 运算符更奇怪。如果你反编译你的代码,你会得到这样的 JS:
kotlin.kotlin.io.output.flush();
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'moduleId'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'moduleId'.");
}
var moduleId = function (_, Kotlin) {
'use strict';
var equals = Kotlin.equals;
var println = Kotlin.kotlin.io.println_s8jyv4$;
function main(args) {
var value = 'something';
println(equals(value.toUpperCase().toLowerCase(), value)); // NOTE: equals
println(value.toUpperCase().toLowerCase() === value); // NOTE: ===
}
_.main_kand9s$ = main;
main([]);
Kotlin.defineModule('moduleId', _);
return _;
}(typeof moduleId === 'undefined' ? {} : moduleId, kotlin);
kotlin.kotlin.io.output.buffer;
Run Code Online (Sandbox Code Playgroud)
现在,如果您考虑等效的 Java 代码(稍微缩短并且没有 Kotlin):
public static void main(String[] args){
String value = "something";
System.out.println(value.toUpperCase().toLowerCase().equals(value));
System.out.println(value.toUpperCase().toLowerCase() == value);
}
Run Code Online (Sandbox Code Playgroud)
toUpperCase().toLowerCase()创建一个新对象,这会破坏==比较,即身份检查。
虽然===也被概述为身份检查,但a === b如果 a 和 b 是包含相同字符的字符串,则为 true。从反编译的 Kotlin 代码中可以看出,Kotlin.JS 编译为原始字符串,而不是 String 对象。因此,===当你处理原始字符串时,JS 中的 将会返回 true。
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |