Combine Java with Kotlin in Android [closed]

2020-02-23 07:46发布

问题:

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 2 years ago.

I am slightly moving from Java to Kotlin in android app development, but there are some cases where I don't want to code in Kotlin and want those particular cases be written in Java:

  • It is effort-saving that Kotlin removes extra usage of findViewByIds
  • I know that it is now null-safety which oppositely Java always triggered with NullPointerException
  • Lambda expressions are also provided and many other features.

But still, some of my codes cannot be written in Kotlin such as static members or non-primitive fields.

Kotlin annotations actually can replace those static members. But love some coding features of Java and dont want to leave that.

My question is can I combine Java and Kotlin together?

回答1:

If your question is can you use kotlin files in java files and vice versa then the answer is yes.

If you are asking if you can use kotlin syntax in java files and vice versa then the answer is no.

To use kotlin code in a java class you are simply using the class like any other java class



回答2:

You can create a java similar static variables using companion object.

You can easily create singleton in Kotlin using object.

After I leant kotlin. I have migrated all my codes to Kotlin.



回答3:

You can have in your project Java and Kotlin Class and Activities.

The same Class can't have Java and Kotlin. You can convert a Java file to Kotlin with Ctrl+Alt+Shift+K or just double tap SHIFT and search for Convert Java to Kotlin



回答4:

Even if it's interop you can't mix Java and Kotlin in the same file.

If you really want to have static methods/variables you can use an companion object. You can also access create a "real" static method in your JVM by using @JvmStatic.

Simple sample is:

companion object {  
    @JvmStatic 
    fun newInstance() ) SampleFragment()
}

which equals to

public static SampleFragment() { return new SampleFragment(); } 

By using @JvmStatic you can use Java to access your Static methods like before.