Error when trying to create a view model factory class in Android Kotlin

Viewed 55

I get this error when trying to create a view model factory class. I have no idea to fix this. Can anyone help me please?

Inheritance from an interface with '@JvmDefault' members is only allowed with -Xjvm-default option

Error

ViewModel Factory

class NewTagViewModelFactory(private val repository: PomodoroRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
    if (modelClass.isAssignableFrom(NewTagViewModel::class.java)) {
        @Suppress("UNCHECKED_CAST")
        return NewTagViewModel(repository) as T
    }
    throw IllegalArgumentException("Unknown ViewModel class")
}

}

1 Answers

You have to specify jvm-default option in kotlin compiler arguments.

Here is an example for build.gradle.kts

android { ... }

// version 1
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().all {
  kotlinOptions.freeCompilerArgs += listOf(
    "-Xopt-in=kotlin.RequiresOptIn",
    // ... other compiler arguments
    "-Xjvm-default=all",
  )
}

// version 2
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().all {
  kotlinOptions.freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn",
  // ... other compiler arguments
  kotlinOptions.freeCompilerArgs += "-Xjvm-default=all"
}
 
dependencies { ... }
Related