Fixing the “Cannot Inline Bytecode Built With JVM Target 1.8 . . .” Error

--

Today I was learning and playing around with Android ViewModels. According to the Android Developer page on ViewModels, the recommended way to access a ViewModel from a Fragment, when programming in Kotlin, is to use the by activityViewModel() property delegate, like so:

val viewModel: MyViewModel by activityViewModels()

However, when I added that line, I got the following error in Android Studio: Cannot inline bytecode build with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option .

I did not know how to fix this, and there were no contextual suggestions for fixing it. So I decided to just “make” my project to see if maybe a build would make the error go away. It did not. I got the same error.

But this time, there was an action I could click to fix it. So I did, and I got the following prompt for refactoring:

After clicking “Do Refactor”, the following lines got added to the android section of my app’s build.gradle file:

android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}

...
}

After syncing Gradle and rebuilding the project, the error went away.

So it turns out that if you get the above error, adding the above lines to the android section in your Gradle file may be a way to fix it.

And it turns out, the Android Developer website has an article that describes this in detail: using Java 8 features and APIs.

Now I know.

--

--

Brian Terczynski

Documenting my learnings on my journey as a software engineer.