简体   繁体   中英

How to use a Kotlin class in a java class?

I am newbie in Kotlin programing. I am developing an Android app, where I use Java for development. After Google announced, Kotlin as official for Android development, I wnated to try the features added up to my android app in Kotlin. So I started with a POJO class.

I have a pojo classs say MyPOJO.kt in the package, com.example.model I am trying to use that pojo in another java class MyViewModel.java in the package com.example.viewmodel

When I tried to run my app, I get an exception like, /Users/senthil/app/src/main/java/com/example/viewmodel/MyViewModel.java Error:(17, 35) error: cannot find symbol class MyPojo

I couldn't figure out what the problem is.

Thanks in advance

The most likely error seems to be that you're missing something in your Kotlin setup.

For a pre-3.0 Android Studio setup, you should have the following in your apps build.gradle:

apply plugin: 'kotlin-android'

dependencies {
  ...
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

And the following in your top-level gradle:

buildscript {
  ext.kotlin_version = '1.1.2-3'
  repositories {
    jcenter()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

allprojects {
  repositories {
    jcenter()
  }
}

And of course the kotlin plugin installed.

Depending on your src file structure, you might also need to add something like this:

sourceSets {
  main.java.srcDirs += 'src/main/kotlin'
  test.java.srcDirs += 'src/test/kotlin'
}

But that's only necessary if you insist on having kotlin files in a separate directory (currently, I tend not to do so).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM