kotlin function default arguments from java

前端 未结 2 1133
眼角桃花
眼角桃花 2021-02-11 14:21

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:55

    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!

提交回复
热议问题