DEV Community

Stone
Stone

Posted on

kotlin learning notes Ⅴ—— kotlin and java

Mutual call between kotlin and Java

If you declare a function in kotlin, how do you call it in Java?
Suppose that in the KotlinDemo.kt file Write a kotlin function in the file:

fun getName(name:String):String{

    return name;
}

Then, we create a new Java file called javademo. How do we call the function getName in the file KotlinDemo.kt?

    public static void main(String[] args){
        KotlinDemoKt.getName("I am xxx");
    }

As we can see, we can call this function only by using the file name in kotlin and the function name to be called in the java file. The format is:
. to be called
This way you can call the Kotlin function in Java.

Anonymous Inner Class in kotlin

object Test{
    fun sayHello(){
        print("hello!!");
    }
}

Using anonymous inner class in kotlin is very simple. You can use type directly. Function name can be used

fun getTest(){
    Test.sayHello();
}

How to use it in Java? It's also very simple

  public static void main(String[] args){
        Test.INSTANCE.sayHello();
    }

static in kotlin

There is no concept of static variables and static methods in kotlin, that is, there is no static keyword in kotlin. So what if we want to have a method similar to public static in Java in kotlin? In fact, this is also very simple. We only need a modifier @ jvmstatic to modify the sayhello function

object Test{
    @JvmStatic
    fun sayHello(){
        print("hello!!");
    }
}

In this way, sayhello becomes a static method, which can be used directly in Java Test.sayHello () instead of using instance.

Top comments (0)