Combining Java with Kotlin on Android

I’m moving a bit from Java in Kotlin to developing Android applications, but there are some cases when I don’t want to code in Kotlin and want these specific cases written in Java:

  • It’s a saving of effort that Kotlin removes additional usage findViewByIds
  • I know that now null-safety, against which Java always starts withNullPointerException
  • Lambda expressions and many other functions are also provided.

But still, some of my codes cannot be written to Kotlin, for example, staticmembers or non-primitive.

Kotlin annotations can actually replace those static members. But love some Java coding features and don't want to leave this out.

My question is: can I combine Java and Kotlin together?

+4
source share
4 answers

If you ask a question if you can use kotlin files in java files and vice versa then the answer will be yes.

If you ask if you can use kotlin syntax in java files and vice versa then the answer will be negative.

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

+3
source

You can create Java-like static variables using a companion object .

You can easily create a singleton in Kotlin using an object .

After I lowered the cauldron. I transferred all my codes to Kotlin.

+2
source

, Java Kotlin .

/, companion object. "" JVM @JvmStatic.

:

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

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

@JvmStatic, Java , .

+1

Java Kotlin.

Java Kotlin. Java Kotlin Ctrl + Alt + Shift + K SHIFT Java Kotlin

0

Source: https://habr.com/ru/post/1685898/


All Articles