Home > Software engineering >  Android studio - kotlin class not found when implementing in java file - error "cannot find sym
Android studio - kotlin class not found when implementing in java file - error "cannot find sym

Time:01-12

I am trying to use a kotlin class in my java class in android studio. But I get the following error twice...

"cannot find symbol class KotlinClass"

KotlinClass is the file name of the kotlin class I am trying to implement.

Both the java and kotlin file are in the same package.

I have tried to put them in different packages but it caused me more problems and so i kept them in the same package but i might have done this so if this is a potential solution, i can try again but i would need more detailed steps if possible.

This error occurs in the build tab.

I have looked into this quite a bit but nothing seems to work.

This is my java class

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        KotlinClass x = new KotlinClass();
        x.kotlinMethod();
    }
}

This is my kotlin class

lass KotlinClass {
    fun kotlinMethod() {
        println("You did it again!!!")
    }
}

Im very new to android studio, any help will be appreciated

CodePudding user response:

I believe that your issue is that you have created the project as a Java project and a Java project doesn't support Kotlin directly.

If you create the project as a Kotlin Project e.g.

enter image description here

Then Kotlin supports Java from the onset. The only issue is that the Activity will then be in Kotlin.

To circumvent this, as was done below, you could add another Activity set it to be Java, and then use this to replace the Kotlin activity (not sure why other than to do it though).

The following demonstrates:-

enter image description here

  • i.e. the project comppiled and ran on the emulator.
  • as can be seen MainActivity (with some manipulation) is Java
  • KotlinClass is Kotlin

CodePudding user response:

Create Kotlin class like this and keep rest the same.

enter image description here

  • Related