Martin Marconcini
Martin Marconcini

Reputation: 27236

Kotlin javaClass<> missing dependency in latest Android Studio 3.0

Toolchain:

Problem: javaClass<> is missing and Android Studio can't "import it".

What I did:

  1. Create new Android project, target API 23 and told it to include a "basic activity".

  2. Added the Gradle dependencies for ViewModel and Room taken from: https://developer.android.com/topic/libraries/architecture/adding-components.html

These are the lines I added to my App Module's gradle file:

compile "android.arch.lifecycle:runtime:1.0.0-alpha1"
compile "android.arch.lifecycle:extensions:1.0.0-alpha1"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"    
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
  1. The Kotlin reference in the same Gradle is: compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" (I didn't add that one, came automatically)

  2. I then created a simple Kotlin class called MainViewModel:

    import android.arch.lifecycle.ViewModel class MainViewModel : ViewModel() {}

  3. Then I went to my Activity and tried to do what this Google Documentation says: https://developer.android.com/topic/libraries/architecture/viewmodel.html

It's in Java but converted to Kotlin, I think it should look like:

val mainViewModel = ViewModelProviders.of(this).get(javaClass<MainViewModel>)

The problem is that Android Studio is not finding javaClass and the fix (to press ) doesn’t do anything.

Android Studio screen shot

What am I missing?

Upvotes: 2

Views: 2730

Answers (1)

Martin Marconcini
Martin Marconcini

Reputation: 27236

I decided to try to use the Java To Kotlin conversion. So I created a new Activity in Java, and wrote the above code as the java documentation states.

After the class was working, I did Code -> Convert Java Class To Kotlin in Android Studio, and the resulting Kotlin class had the following line:

val viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

This compiled perfectly. I will have to learn more about which one is correct, but this one may save you some time if you’re, like me, new to the language.

Upvotes: 5

Related Questions