【错误记录】Kotlin 编译报错 ( Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable ... )

简介: 【错误记录】Kotlin 编译报错 ( Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable ... )

文章目录

一、报错信息

二、解决方案





一、报错信息


Google Play 上架要求 Android 的编译版本 和 目标版本都要高于 30 才可以上传 ;


image.png


将 Android 的编译版本 和 目标版本 都升级为 30 3030 之后 , 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"
  }
}



编译时报错如下 :


Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Window?


image.png


在 编译版本 compileSdkVersion 和 目标版本 targetSdkVersion 都为 28 2828 时 , 编译不报上述错误 ;


改了下 Android 编译版本号 , 报了 286 286286 个错误 , 今天逐个解决上述编译错误 ;






二、解决方案


错误分析 :


非空类型 与 可空类型 变量的调用问题 ;


val window = dialog.window
val attributes = window.attributes


val window 没有声明变量类型 , 使用自动推断确定变量类型 , 而系统自动推断为 Window! 类型 , 这是可空类型 ;



如果调用可空类型的成员方法 或 成员变量 , 则必须使用 ? 或者 !! ;



解决方案 :


上述问题有两种解决方案 , 可以将该变量转为非空类型的变量 , 也可以在调用时加上 ? 或 !! 修饰该调用 ;


方案一 : 将该变量转为非空类型的变量


val window = dialog.window!!
val attributes = window.attributes


方案二 : 调用时加上 ? 或 !! 修饰该调用


val window = dialog.window
val attributes = window?.attributes



val window = dialog.window
val attributes = window!!.attributes



目录
相关文章
|
9月前
|
容器
Echarts报错 Cant read property getWidth of null的解决方案
Echarts报错 Cant read property getWidth of null的解决方案
81 0
|
JSON 前端开发 API
【跨域报错解决方案】Access to XMLHttpRequest at ‘http://xxx.com/xxx‘ from origin ‘null‘ has been blocked by
【跨域报错解决方案】Access to XMLHttpRequest at ‘http://xxx.com/xxx‘ from origin ‘null‘ has been blocked by
1867 0
|
6月前
|
缓存 关系型数据库 MySQL
【异常解决】缓存报错:Null key returned for cache operation (maybe you are using named params on classes withou
【异常解决】缓存报错:Null key returned for cache operation (maybe you are using named params on classes withou
206 0
|
3月前
|
Java 编译器 API
告别KAPT!使用 KSP 为 Kotlin 编译提速
告别KAPT!使用 KSP 为 Kotlin 编译提速
114 0
|
6月前
|
缓存 Cloud Native JavaScript
猫头虎的技术博客:解决npm报错 npm ERR! Cannot read properties of null (reading ‘pickAlgorithm‘)报错问题
猫头虎的技术博客:解决npm报错 npm ERR! Cannot read properties of null (reading ‘pickAlgorithm‘)报错问题
114 0
|
9月前
|
JavaScript
解决npm ERR! Cannot read properties of null (reading ‘pickAlgorithm‘)报错问题
在vue项目中,使用npm i 命令安装node modules时,出现报错。
|
10月前
|
Dart 安全
Flutter开发Cannot run with sound null safety报错
Flutter开发Cannot run with sound null safety报错
|
10月前
springSecurity报错:Cannot pass a null GrantedAuthority collection
springSecurity报错:Cannot pass a null GrantedAuthority collection
87 0
|
10月前
|
存储 缓存 KVM
KVM创建存储池中报错:确认输入时未捕获的错误:constructor returned null解决
KVM创建存储池中报错:确认输入时未捕获的错误:constructor returned null解决
154 0
|
11月前
|
SQL 监控 druid
事务未能正确提交导致Druid报错connection holder is null(2)
事务未能正确提交导致Druid报错connection holder is null(2)
721 0