Kotlin “also” function strange warning in Android Studio

十年热恋 提交于 2021-02-08 15:43:13

问题


There is two presumably identical snippets:

// Verbose version
val typedArray = context.obtainStyledAttributes(attrs, styleable)
block(typedArray)
typedArray.recycle()
// One-line version
context.obtainStyledAttributes(attrs, styleable).also(block).recycle()

I'm wonder why verbose block of code looks fine to Android Studio, whereas one-line version highlights obtainStyledAttributes and gives following warning:

This TypedArray should be recycled after use with #recycle()

Does anyone know is it just an Android Studio lint check flaw or something is actually wrong with one-line version?


回答1:


This is a bit of a guess, but I believe it's because the static analysis tool can't guarantee that the TypedArray returned by also() is the same instance as the one returned by obtainedStyledAttributes(). It sees that a TypedArray is obtained but can't guarantee that it is recycled, so it issues the warning.

I would hesitate to call this a bug (or "flaw") in the linter, but it does mean that the warning can be ignored in this case.



来源:https://stackoverflow.com/questions/57225133/kotlin-also-function-strange-warning-in-android-studio

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