Kotlin Android Studio-Var在SDK 29中被视为val [英] Kotlin Android Studio - Var is seen as val in SDK 29

查看:104
本文介绍了Kotlin Android Studio-Var在SDK 29中被视为val的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在科特林遇到了一件很奇怪的事情. 我有

I'm experiencing a pretty strange thing in Kotlin. I have

var myClipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager?
var myClip: ClipData? = ClipData.newPlainText( /* my code */ )

作为var变量,我应该能够重新分配他的值,但是当我这样做时

As a var variable, I should be able to reassign his value, but when I do

myClipboard?.primaryClip = myClip

它给了我错误

无法重新分配Val

Val cannot be reassigned

最奇怪的是,我已经使用了几周的这段代码,并且一直有效.今天,当我更新为API 29时,它停止工作

The strangest things is that I'm using this code by weeks and it always worked. It stopped working today when I updated to API 29

这是我的build.gradle android{}

    android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "com.arfmann.pushnotes"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 16
        versionName "1.6"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

推荐答案

ClipboardManager文档getPrimaryClip返回ClipData?(即,可为空的ClipData),而setPrimaryClip()接受ClipData-非null ClipData.

As seen in the ClipboardManager documentation, getPrimaryClip returns a ClipData? (i.e., a nullable ClipData) while setPrimaryClip() takes a ClipData - a non-null ClipData.

当类型不同(并且可空性是Kotlin输入的重要组成部分)时,Kotlin不支持var属性访问,因此,当您调用primaryClip时,Kotlin仅可以有效地给您提供val等效项.

Kotlin does not support var property access when the types are different (and nullability is an important part of Kotlin typing) therefore Kotlin can only give you effectively the val equivalent when you call primaryClip.

在API 29中添加了setPrimaryClip上的可空性注释,这就是为什么在升级compileSdkVersion后行为会有所不同的原因.

The nullability annotation on setPrimaryClip was added in API 29, which is why the behavior is different once you upgrade your compileSdkVersion.

要设置主剪辑,您必须明确地将setPrimaryClip()与非null ClipData一起使用,或者在API 28+上,使用

To set the primary clip, you must explicitly use setPrimaryClip() with a non-null ClipData or, on API 28+, use clearPrimaryClip() to completely clear the primary clip.

这篇关于Kotlin Android Studio-Var在SDK 29中被视为val的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆