Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have following code that produces following lint error. lint issue

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: decompiled

Which do reference Bundle type not a BaseBundle.

Why do we have Lint error in first place?

like image 864
Tom Koptel Avatar asked Jul 31 '17 12:07

Tom Koptel


2 Answers

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.

like image 95
lelloman Avatar answered Sep 19 '22 23:09

lelloman


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
        }
    }
}
like image 32
Kevin Robatel Avatar answered Sep 21 '22 23:09

Kevin Robatel