您可以更新build.gradle
文件以将模块正确配置为Kotlin库,方法是替换id("java-library")
with id("org.jetbrains.kotlin.jvm") version "<kotlin_version>"
,并包括Kotlin标准库和任何其他特定于Kotlin的依赖项:
plugins {
id("org.jetbrains.kotlin.jvm") version "<kotlin_version>"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}
kotlin {
sourceSets {
main {
kotlin.srcDirs("src/main/kotlin")
}
test {
kotlin.srcDirs("src/test/kotlin")
}
}
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
There is an optional kotlin
block to set source directories. The java
block is for compatibility settings.
Sync your Gradle files after making these changes.
关于LiveData lint警告,try 修改您的ViewModel
以处理可为空的MediaContent
:
private val _cropRequiredLiveData = SingleLiveEvent<MediaContent?>()
fun crop(): LiveData<MediaContent?> = _cropRequiredLiveData
private fun onDownloadComplete(content: MediaContent?) {
if (request.isCropEnabled && content != null) {
_cropRequiredLiveData.value = content
}
//
}
_cropRequiredLiveData
被声明为SingleLiveEvent<MediaContent?>
以接受可为空的值.这一更改要求在观察到_cropRequiredLiveData
的代码部分中处理为空性.
或者:如果将content
赋值给_cropRequiredLiveData
时确定content
非空,则在if
条件中勾选content != null
后可以为use !!
:
private fun onDownloadComplete(content: MediaContent?) {
if (request.isCropEnabled && content != null) {
_cropRequiredLiveData.value = content!!
}
//
}
Although, I updated the projects as you said, it didn't help me resolve both the issues.
But, to be fair, I found out that "Java Enum Nullability
" issue only happens when I observe any enum
using LiveData
(which is a java class), and not because the enum
class was declared in another module.
因此,当观察LiveData
个枚举时,"Java Enum Nullability"问题浮出水面,这确实是一个Java类.这可能是因为Kotlin和Java处理空性的方式不同,以及Kotlin与Java代码交互的方式.
在Java中,所有非基元类型都可以为空,包括枚举.当Kotlin与Java类型交互时,为it often treats them as nullable以维护Java的可空性契约.这可能就是为什么在将LiveData
与枚举一起使用时,您会看到与枚举为空性相关的警告.
为了解决这个问题,在观察枚举到LiveData
时,显式判断null值,即使这在Kotlin中似乎是不必要的.这种方法确保了在处理来自Java类的潜在空值时的安全性.
myEnumLiveData.observe(this, Observer { enumValue ->
if (enumValue != null) {
// Handle non-null enum case
} else {
// Handle null case, even if it is unexpected in Kotlin
}
})
另一种可能的方法是:为LiveData
创建一个强制非空值的定制包装器.这可以帮助弥合Kotlin的非空类型和LiveData的基于Java的空性之间的差距.
class NonNullLiveData<T : Any>(private val liveData: LiveData<T?>) : LiveData<T>() {
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
liveData.observe(owner, Observer { it?.let(observer::onChanged) })
}
}
使用此包装器观察枚举,隐式过滤掉空值.
或者,在处理可能为空的LiveData值时,也可以使用Kotlin的safe calls (?.
)和Elvis operator (?:
).
myEnumLiveData.observe(this, Observer { enumValue ->
val safeEnumValue = enumValue ?: return@Observer // Handle or return on null
// Use safeEnumValue which is guaranteed non-null here
})