android studio val,Kotlin Android Studio - Var is seen as val in SDK 29

在更新Kotlin项目到API 29后,开发者遇到一个关于ClipboardManager的奇怪问题。之前能够正常工作的代码在更新后报错,提示无法重新分配val的值。问题在于`getPrimaryClip()`返回的是 nullable 的 `ClipData?`,而 `setPrimaryClip()` 需要非空的 `ClipData`。解决方案是使用非空的ClipData或在API 28+上使用 `clearPrimaryClip()` 清除主剪贴板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

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 */ )

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

myClipboard?.primaryClip = myClip

It gives me the error

Val cannot be reassigned

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

This is my 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'

}

}

}

回答1:

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 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.

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

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.

回答2:

Here is the working copy,

val myClipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager?

val myClip: ClipData? = ClipData.newPlainText("", "")

myClipboard?.primaryClip = myClip

Hope this can help you

来源:https://stackoverflow.com/questions/57128725/kotlin-android-studio-var-is-seen-as-val-in-sdk-29

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值