为了验证类成员身份,
in
和 instanceof
关键字似乎表现相同。那么两者之间有什么区别呢?它们是否真的有区别?在 StackOverflow 上有几个问题(这里 或 这里)给出了这两个关键字作为解决方案,但没有提到它们之间的区别或何时更适合使用其中之一。此外,官方文档提到 in
关键字等同于调用对象的 isCase()
方法, 但没有详细说明 instanceof
关键字的作用。
这两个关键字在类继承和接口实现方面似乎表现相同:
class MyMap extends LinkedHashMap { }
def foo = new LinkedHashMap()
def bar = new MyMap()
println("LinkedHashMap instance is 'in' LinkedHashMap: ${foo in LinkedHashMap}")
println("LinkedHashMap instance is 'instanceof' LinkedHashMap: ${foo instanceof LinkedHashMap}")
println("LinkedHashMap instance is 'in' Map: ${foo in Map}")
println("LinkedHashMap instance is 'instanceof' Map: ${foo instanceof Map}")
println("MyMap instance is 'in' LinkedHashMap: ${bar in LinkedHashMap}")
println("MyMap instance is 'instanceof' LinkedHashMap: ${bar instanceof LinkedHashMap}")
println("MyMap instance is 'in' Map: ${bar in Map}")
println("MyMap instance is 'instanceof' Map: ${bar instanceof Map}")
输出:
LinkedHashMap instance is 'in' LinkedHashMap: true
LinkedHashMap instance is 'instanceof' LinkedHashMap: true
LinkedHashMap instance is 'in' Map: true
LinkedHashMap instance is 'instanceof' Map: true
MyMap instance is 'in' LinkedHashMap: true
MyMap instance is 'instanceof' LinkedHashMap: true
MyMap instance is 'in' Map: true
MyMap instance is 'instanceof' Map: true
someObject instanceof SomeClass
与someObject in SomeClass
的行为会有所不同(除了覆盖isCase()
)。根据给定的信息,似乎在所有实际目的下,这两者的行为都是相同的,即使它们不是严格等价的。 - jayhendrenObject in Class
-> false.Object instanceof Class
-> true. - jayhendren