简体   繁体   English

为什么此 Kotlin 扩展未能通过 Android Studio Lint 检查?

[英]Why is this Kotlin extension failing Android Studio Lint checks?

Within Android development, there is often a time in which a block of code needs to be executed if and only if the device's SDK is greater than or equal to a minimum version.在 Android 开发中,当且仅当设备的 SDK 大于或等于最低版本时,通常会有一段代码需要执行的时候。

To avoid the often ugly and repetitive nature of this code, I created the following extension.为了避免这段代码通常丑陋和重复的性质,我创建了以下扩展。

inline fun <T> runWithMinSdk (minVersion: Int, func: () -> T) {
    if (android.os.Build.VERSION.SDK_INT >= minVersion) { func() }
}

Nothing too fancy, and seems to do the trick on paper.没有什么太花哨的,似乎在纸上做的伎俩。

However , when I use this code as such:但是,当我使用此代码时:

fun myFun {
    runWithMinSdk(Build.VERSION_CODES.O) {
        exampleMethodThatRequiresOreo()
    }
}

Android Studio throws a hissy fit and it fails the Lint checks, asking to either suppress 'NewApi' warnings within myFun() or wrapping the runWithMinSdk block with if android.os.Build.VERSION.SDK_INT ... etc Android Studio 发出嘶嘶声,并且 Lint 检查失败,要求在myFun()取消“NewApi”警告或使用if android.os.Build.VERSION.SDK_INT ... etc包装runWithMinSdk

Is there a better way to achieve this functionality, make it pass the Lint checks or is none of this possible using extensions?是否有更好的方法来实现此功能,使其通过 Lint 检查,或者使用扩展都无法实现?

Based on this this discussion in the Kotlin forum it seems like doing something like this isn't possible, because Lint can only look at the current function for annotations. 基于此在Kotlin论坛中的讨论 ,似乎做这样的事情是不可能的,因为Lint只能查看注释的当前函数。 For instance if you do 例如,如果你这样做

val func = @TargetApi(26) { exampleMethodThatRequiresOreo() }
runWithMinSdk(Build.VERSION_CODES.0, func)

you won't get the warning, but that also kinda defeats the purpose of this extension function. 你不会得到警告,但这也有点违背了这个扩展功能的目的。 The OP in the discussion above mentions taking the feature request to Anko, but I couldn't find an associated issue there. 上面讨论中的OP提到了向Anko提出功能请求,但我找不到相关的问题。

The androidX annotation library provides a nice solution for this: androidX 注释库为此提供了一个很好的解决方案:

@ChecksSdkIntAtLeast(parameter = 0)
inline fun <T> runWithMinSdk(minVersion: Int, func: () -> T) {
    if (android.os.Build.VERSION.SDK_INT >= minVersion) { func() }
}

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

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