Interoperability between Kotlin and Java


#1

Hi All,

I have developed an android app which written in Java. Now I am going to add a new feature to it. I want to implement it in Kotlin as Kotlin supports the interoperability with java.
I facing some problems
Eg: 1) I need to load/replace Fragment which is coded in Kotlin from the Activity which is coded in Java.
2) Passing data to Kotlin fragment/Activity from Java Fragment/Activity
3) Converting/Casting Objects from Kotlin to Java and Java to Kotlin.

Thank You,
Ravi.


#2

Kotlin objects are java objects. Basically they are fully interoperable and interchangeable. If the Java activity wants to use a fragment written in Kotlin it uses exactly the same code as if it were written in Java. The same way with passing data (you set it as extra on the intent that starts the activity / or the fragment parameters) - nothing different. On converting/casting you don’t need to do so, both languages produce class files that are compatible with eachother and all get transformed into dex later.


#3

I am trying to make some changes in google sample project

I have rewritten written one fragment BasicAndroidKeyStoreFragment in kotlin ( the fragment was originally written in java)

Now in MainActivity.java, I have following piece of code originally to add BasicAndroidKeyStoreFragment

BasicAndroidKeyStoreFragment fragment = new BasicAndroidKeyStoreFragment();
transaction.add(fragment, FRAGTAG);
transaction.commit();

Now I crated a replica fragment in kotlin AndroidKeyStoreFragmentKotlin.kt
Just wanted to know how to add above kotlin fragment in MainActivity.java.