Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

given following Kotlin class:

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

How should I call 'bar' function without any parameter from a java/groovy code?

def f = new Foo()
f.bar() //throws:  java.lang.IllegalArgumentException: Parameter specified as non-null contains null
question from:https://stackoverflow.com/questions/17348084/kotlin-function-default-arguments-from-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
314 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...