3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

@JvmOverloadsとは

Posted at

JavaからKotlinのデフォルト値を持つクラス、または関数を呼び出せるようにするアノテーション。

Javaでデフォルト値はサポートされていないため、以下のGreeting#sayHelloを呼び出すとコンパイルエラーになります。

NG

class Greeting {
    
    fun sayHello(prefix: String = "Mr.", name: String) {
        println("Hello, $prefix $name")
    }
}
public class JavaClass {
    public static void main(String[] args) {
        Greeting greeting = new Greeting();
	// prefixを引数に渡していないのでエラーになる。
        greeting.sayHello("Bob");
    }
}

Greeting#sayHello@JvmOverloadsを付与することで、Javaからデフォルト値を持つ関数を呼び出せるようになります。

OK

class Greeting {
    @JvmOverloads
    fun sayHello(prefix: String = "Mr.", name: String) {
        println("Hello, $prefix $name")
    }
}
public class JavaClass {
    public static void main(String[] args) {
        Greeting greeting = new Greeting();
        greeting.sayHello("Bob");
    }
}

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?