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

文章目录





一、报错信息



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

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

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

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

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

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





二、解决方案



错误分析 :

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

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

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

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

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


解决方案 :

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

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

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

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

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

val window = dialog.window
val attributes = window!!.attributes
上一篇:基于python对B站收藏夹按照视频发布时间进行排序


下一篇:eas之日期控件