问题

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

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐