DEV Community

Stone
Stone

Posted on

1

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.

Image of Stellar post

From Hackathon to Funded - Stellar Dev Diaries Ep. 1 🎥

Ever wondered what it takes to go from idea to funding? In episode 1 of the Stellar Dev Diaries, we hear how the Freelii team did just that. Check it out and follow along to see the rest of their dev journey!

Watch the video

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay