Chapter 13: Fragment Navigation - Problem with ViewModelFactory

I am trying to create a ViewModel Factory with the below code:

class CrimeDetailViewModelFactory(private val crimeId: UUID) : ViewModelProvider.Factory {
override fun create(modelClass: Class): T {
return CrimeDetailViewModel(crimeId) as T
}
}

However, against the class definition, there is a compilation error saying:

Inheritance from an interface with ‘@JvmDefault’ members is only allowed with -Xjvm-default

Can someone kindly explain what I miss?

Had to include the below in kotlinOptions in build.gradle(app) file to solve this.

kotlinOptions {
freeCompilerArgs += [
“-Xjvm-default=all”,
]
jvmTarget = ‘1.8’
}

Glad you were able to solve this on your own. Technically speaking, all you need is that jvmTarget = ‘1.8’ line. You do not need to add the freeCompilerArgs chunk.

This line should have been included into your project when it was generated. I am not sure what version of Android Studio you are using, but I know it does that as of Android Studio version 2021.2.1 Patch 1.

EDIT: I did a little more digging and found this issue (Google Issue Tracker). It looks like you could run into this issue depending on the version of Kotlin you are using. You do not ever manually provide that while working through the book. The solutions we provide use version 1.6.10, as you can see in the Project build.gradle file.

1 Like

Thanks for the reply!

1 Like

I was having a similar type of issue. I tried implementing this inside my build.gradle:

kotlinOptions {
        freeCompilerArgs += [
                "-Xjvm-default=all",
        ]
      ...
    }

However, this solution didn’t work for me.

But after reading @bryansillsbnr post, especially the Google Issue Tracker link:

We may want to use all-compatibility instead of all in some circumstances.
So instead, I added this to my build.gradle file, and it finally builds.

kotlinOptions {
        freeCompilerArgs += [
                "-Xjvm-default=all-compatibility",
        ]
      ...
    }

It looks like we might need to do this since we are using Kotlin version 1.6.10. The user in the issue tracker mentioned that starting version 1.6.20 we won’t need to manually add that to the build.gradle file. That said, we might get this issue on the version older than 1.6.20.