Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 为什么Kotlin(社区)鼓励模式匹配中的反射_Android_Kotlin_Reflection_Pattern Matching - Fatal编程技术网

Android 为什么Kotlin(社区)鼓励模式匹配中的反射

Android 为什么Kotlin(社区)鼓励模式匹配中的反射,android,kotlin,reflection,pattern-matching,Android,Kotlin,Reflection,Pattern Matching,几乎每一个KotlinAndroid教程或项目都会大量使用when结构,如下所示 val response : Response = //... when(response){ is Success -> useResponseData(response.data) is Cancelled -> handleCancellation() is Error -> handleError(response.errorCode) } 据我所知,反射

几乎每一个
Kotlin
Android教程或项目都会大量使用
when
结构,如下所示

val response : Response = //...
when(response){
   is Success   -> useResponseData(response.data)
   is Cancelled -> handleCancellation()
   is Error     -> handleError(response.errorCode) 
}
据我所知,反射的使用在大多数情况下是不合理的,应该避免。我假设我的例子就是这样一种特殊情况,即反射的使用是合理的,前提是
响应
密封的
,并且它的子类集很可能永远不会改变。我说得对吗


在我的示例中,这样的构造是绝对“干净”的,还是为了代码的简单性而做出的妥协?

我想问的是,是否对类进行了强制转换或检查,甚至认为是反射?这只是一个基本的多态操作。我找到了这个答案:关于你的问题。然而,与此同时,wiki谈到类型内省:“内省不应该与反射混淆。”我认为真正的“多态”解决方案是在这种情况下使用访问者模式。这将是一种没有密封类的代码味道,但即使如此,有时,使用多态性来解决问题比使用多态性更好。但是对于密封类,反对使用
is
的论点被消除了。它简单且可维护,这是反对在没有密封类的情况下使用
is
的两个主要论点。