Kotlin Android Studio - Var is seen as val in SDK 29
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.
Use it like this
val clipboard = ctx.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Beacon infos", it.toJson())
clipboard.setPrimaryClip(clip)