Call Kotlin from Java
These days, developing Android app by kotlin becomes popular. But, sometimes we need to support Java App, continues from the past.
I developed Kotlin base mobile SDK, and some customers need to use this SDK from Java
Kotlin Object and Companion Object
When creating SDK in kotlin, there are 2 types of Java static like method in kotlin
Object and Companion Object.
Object : Top level Kotlin object
Companion Object : In class, create object under class (only one companion object into class)
To make under above, Kotlin can create Java static like
Example
Let’s create Example.
Prepare sample Project and Create
Activity : Java
Object : Kotlin
Class + Companion Object : Kotlin
Call Object and Companion Object from Java Activity
ObjectA.kt
object ObjectA { fun methodA() : String { return "MethodA" } }
CompanionB.kt
class CompanionB { companion object CompanionInner { fun methodB() : String { return "methodB" } } }
MainActivity.java
Let’s call above 2 from Java.
To call Object for kotlin use “INSTANCA“. This is answer
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ObjectA.INSTANCE.methodA(); // Object CompanionB.CompanionInner.methodB(); // Companion Object } }
Companion Object is simple, just use companion object name.
コメント