简体   繁体   中英

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> <? extends BaseActivity> . This is how I declared the variable in 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"

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. The following code:

activityClass = SpecificActivity::class.java

gives me an error "Type inference failed. Expected type mismatch: required Class<MainActivity> , found 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. The solution is not to turn these options off because I actually want them to be set to 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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