Google Play 上架要求 Android 的编译版本 和 目标版本都要高于 30 才可以上传 ;
将 Android 的编译版本 和 目标版本 都升级为
之后 , Kotlin 的编译检查变得更严格 , 之前不规范的代码需要逐个修改 ;
将编译版本 compileSdkVersion 和 目标版本 targetSdkVersion 由 28 修改为 30 ;
android {
compileSdkVersion 30
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.xxx.xxx"
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "0.1"
}
}
编译时报错如下 :
Not nullable value required to call an 'iterator()' method on for-loop range
在 编译版本 compileSdkVersion 和 目标版本 targetSdkVersion 都为
时 , 编译不报上述错误 ;
改了下 Android 编译版本号 , 报了
个错误 , 今天逐个解决上述编译错误 ;
错误分析 :
使用 ForEach 遍历可空类型的集合时 , 会出现此类报错 ; 因为被遍历的集合 files 有可能为空 , 由此可能会产生崩溃 ;
for (file in files){
}
解决方案 :
上述问题有两种解决方案 , 可以将该变量转为非空类型的变量 , 也可以遍历 files.orEmpty() 集合 ;
方案一 : 将该变量转为非空类型的变量
for (file in files!!){
}
方案二 : 遍历 files.orEmpty() 集合 , 如果 files 为空 , 则 files.orEmpty() 会返回空集合 ; 如果 files 不为空 , 则 files.orEmpty() 返回原来的集合 ;
for (file in files.orEmpty()){
}