Kotlin apply() extension lint message in Android Studio 3.0-alpha8

蓝咒 提交于 2019-12-07 03:29:10

问题


I have following code that produces following lint error.

fun newInstance(message: String?): DialogFragment {
    return DialogFragment().apply {
        arguments = Bundle().apply {
            putString("arg", message)
        }
    }
}

The message points out that this reference inside apply() function points to BaseBundle class that is available since API 21 which will crash on lower API. Bundle#putString(key, value) is definitely available on lower versions, but there is an error in Android Studio 3.0-alpha8.

The issue quite strange as I can see decompiled code as this:

Which do reference Bundle type not a BaseBundle.

Why do we have Lint error in first place?


回答1:


One workaround is to use let instead of apply, like:

fun newInstance(message: String?): DialogFragment {
    return DialogFragment().apply {
        arguments = Bundle().let {
            it.putString("arg", message)
            it
        }
    }
}



回答2:


It really looks like a bug It is a known bug but one could actually see why you're getting the warning if looking at Bundle.java source code.

Before api 21 Bundle had a method (check here)

public void putString(@Nullable String key, @Nullable String value)

and the class itself had no super class. From api 21 Bundle extends a newly added BaseBundle class and this method putString had been moved to BaseBundle. So, when you call the method on api 21 and above, the method belongs to BaseBundle, for lower version it belongs to Bundle.

This is somehow related to the apply block because the warning doesn't appear if you call the method on a Bundle-type variable directly.



来源:https://stackoverflow.com/questions/45415947/kotlin-apply-extension-lint-message-in-android-studio-3-0-alpha8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!