0

I have an Android app written in Java and I am trying to write a new feature in Kotlin. So I added a new Kotlin file and IntelliJ offered to setup the project for Kotlin.

The issue is that when trying to create a Kotlin object in Java, compilation fails with

error: cannot find symbol constructor MyClassKt()

My Kotlin file (MyClass.kt):

 val SCREEN = 1;

 class MyClass() {
     fun hello(view: View) {
     } 
 }

In my app module:

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

In my project module:

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

Invocation in Java:

 new MyClassKt();
4
  • 5
    your kotlin class seems to be MyClass and not MyObject ?!! Commented Oct 29, 2019 at 8:45
  • 1
    Did you apply Kotlin plugin? The apply plugin: 'kotlin-android' on the top of your app module. Commented Oct 29, 2019 at 8:45
  • 1
    Could you add how you are invoking it from Java? Commented Oct 29, 2019 at 10:25
  • Thanks all! Updated the question, added the invocation, fixed the typos. Commented Oct 29, 2019 at 23:15

3 Answers 3

1

Make sure you have these plugin on top in the app gradle file

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

And inside dependencies, should be like

dependencies {
def kotlin_version= "2.2.1"
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"       
}
Sign up to request clarification or add additional context in comments.

Comments

0

Remove brackets from kotlin class definition.

class MyClassXD {
    fun hello(view: View) {
    }
}

Probably Java got wild when it saw brackets in classname.

3 Comments

Brackets just says to add constructor without parameters, so it couldn't be a reason.
No argument constructor is created by default if no other constructor defined, so you do not need them.
Of course it is. And for example Android Studio will highlight it if you mention empty primary constructor, because it's useless to print that. I'm just trying to say it can't lead any error - it is just useless.
0

The problem was that Kotlin was creating a MyClassKt for the file (i.e. for accessing the SCREEN variable).

I just needed to use the normal class name and do new MyClass() (no Kt postfix).

Thanks all!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.