简体   繁体   English

在 Kotlin 中使用 'is' 运算符时是否使用了反射

[英]Is reflection being used when using the 'is' operator in Kotlin

As MVI is getting more and more popular in Android development, the use of Sealed classes increases as well.随着MVI在Android开发中越来越流行,Sealed类的使用也越来越多。 And we know that we have to determine the actual type of the Sealed class in order to continue with a particular flow from our logic.我们知道我们必须确定 Sealed class 的实际类型,以便继续我们逻辑中的特定流程。

So does Kotlin use reflection when using the 'is' operator for type checks?那么 Kotlin 在使用is运算符进行类型检查时是否使用了反射? Tried to go through the documentation, but couldn't find anything about that.试图通过文档访问 go,但找不到任何相关信息。 https://kotlinlang.org/docs/typecasts.html https://kotlinlang.org/docs/typecasts.html

Depends on the definition of reflection you're using.取决于您使用的反射定义。 Often “reflection” in the JVM world is used to describe specifically the String-based code meta data inspection from the java.lang.reflect package (or Kotlin reflection dependency) that is considered to be inefficient. JVM 世界中的“反射”通常用于具体描述来自java.lang.reflect package(或 Kotlin 反射依赖)的基于字符串的代码元数据检查被认为是低效的。 But a more general definition of “reflection” is any code introspection.但“反射”的更一般定义是任何代码自省。 is arguably fits the second definition, but it is fast/optimized and not part of the first definition. is说符合第二个定义,但它是快速/优化的,而不是第一个定义的一部分。

The 'is' operator in Kotlin is used for type checks, for example to check if an object is an instance of a particular class or its subclasses. Kotlin 中的“is”运算符用于类型检查,例如检查 object 是否是特定 class 或其子类的实例。 The 'is' operator does not use reflection to perform type checks. 'is' 运算符不使用反射来执行类型检查。 Instead, the type check is done at compile-time, and the generated bytecode contains an instanceof check, which is a standard JVM instruction for performing type checks.相反,类型检查是在编译时完成的,生成的字节码包含一个 instanceof 检查,这是执行类型检查的标准 JVM 指令。

In the case of sealed classes, the use of 'is' operator will not use reflection as well, it's a compile-time check, that's why when using the 'is' operator with a sealed class, the compiler is able to perform type checks and generate the appropriate bytecode at compile-time.在密封类的情况下,'is' 运算符的使用也不会使用反射,它是一个编译时检查,这就是为什么当使用带有密封 class 的'is' 运算符时,编译器能够执行类型检查并在编译时生成适当的字节码。

Using the 'is' operator is much more efficient than using reflection, as it is a compile-time check and it does not require any runtime overhead, while reflection can be relatively slow, as it requires the JVM to perform additional lookups and checks at runtime.使用“is”运算符比使用反射更有效,因为它是编译时检查并且不需要任何运行时开销,而反射可能相对较慢,因为它需要 JVM 执行额外的查找和检查运行。

So, in summary, the 'is' operator in Kotlin does not use reflection for type checks.因此,总而言之,Kotlin 中的“is”运算符没有使用反射进行类型检查。 It's a compile-time check, which is much more efficient than using reflection.这是一个编译时检查,比使用反射更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM