kotlin function default arguments from java

前端 未结 2 1698
面向向阳花
面向向阳花 2021-02-11 14:01

given following Kotlin class:

class Foo {
   public fun bar(i: Int = 0): Int = 2 * i
}

How should I call \'bar\' function without any parameter

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-11 14:39

    You can do this now in Kotlin. For your class method, use the @JvmOverloads annotation.

    class Foo {
        @JvmOverloads public fun bar(name: String = "World"): String = "Hello $name!"
    }
    

    Now simply call it from Java:

    Foo foo = new Foo();
    System.out.println(foo.bar());
    System.out.println(foo.bar("Frank"));
    

    Outputs the following:

    Hello World!

    Hello Frank!

提交回复
热议问题