简体   繁体   English

Kotlin-可能错误地报告了未使用的代码

[英]Kotlin - possibly incorrectly reporting an unused code

I have a base class for all activities in my app. 我的应用程序中有所有活动的基类。 I want a variable activityClass to be of type <? extends BaseActivity> 我希望变量activityClass的类型为<? extends BaseActivity> <? extends BaseActivity> . <? extends BaseActivity> This is how I declared the variable in Kotlin: 这就是我在Kotlin中声明变量的方式:

 var activityClass = MainActivity::class.java as Class<out BaseActivity>

The problem is that in Android studio I get the part " as Class<out BaseActivity> " grayed out and the popup message says: "No cast needed" 问题是,在Android Studio中,我得到了“ as Class<out BaseActivity> ”部分,并且弹出消息显示:“无需as Class<out BaseActivity>

If I follow the AS advice and I remove the casting, I get compiler errors when I am trying to assign the variable using other activities deriving from BaseActivity. 如果我遵循AS的建议并删除了强制转换,则在尝试使用从BaseActivity派生的其他活动来分配变量时,会出现编译器错误。 The following code: 如下代码:

activityClass = SpecificActivity::class.java

gives me an error "Type inference failed. Expected type mismatch: required Class<MainActivity> , found Class<SpecificActivity> ". 给我一个错误“类型推断失败。预期的类型不匹配:必需的Class<MainActivity> ,找到的Class<SpecificActivity> ”。

This causes problems mainly when I am committing code changes because the options "Cleanup" and "Optimize imports" in AS commit wizard are checked, which removes "unused" code (the "as Class" part), which is in fact actually used. 这主要在我提交代码更改时引起问题,因为在AS提交向导中选中了“清除”和“优化导入”选项,这删除了实际上已实际使用的“未使用”代码(“作为类”部分)。 The solution is not to turn these options off because I actually want them to be set to true. 解决方案是不要关闭这些选项,因为我实际上希望将它们设置为true。

If I commit my changes, go to the class where the casting is used and undo the changes, it asks me "Undo Optimize Imports before commit?". 如果我提交更改,请转到使用强制转换的类并撤消更改,它会问我“在提交之前撤消优化导入吗?”。 If I confirm, I get the casting back, so I know this is causing the issue. 如果我确认,则可以恢复投放,所以我知道这是造成此问题的原因。

PS: I use Kotlin 1.0.5-3 PS:我使用Kotlin 1.0.5-3

解决此问题的正确方法是指定变量类型:

var activityClass: Class<out BaseActivity> = MainActivity::class.java

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

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