LoginSignup
0
0

More than 5 years have passed since last update.

[Kotlin]interfaceを継承しているクラス自体を保証して引数に取る

Last updated at Posted at 2016-07-01

次のようなクラスがあったとします。

class Cat: Animal() {}
class Fox: Animal(),Growlable {}
class Dog: Animal(),Growlable {}

Growlable interfaceを実装しているクラスのみを引数に取りたい場合

fun showTooth(growlableAnimal: Growlable) {
}

と指定すればいいです。
使う時は

showTooth(Cat()) //ng
showTooth(Fox()) //ok
showTooth(Dog()) //ok

ではインスタンスを生成したくない時など、クラス自体を取る時はどうすればいいのでしょうか
Javaでは

public void showTooth(Class<? extends Growlable > growlableClass) {
}

と書けました。
Kotlinでは

fun showTooth(growlableClass: Class<out Growlable>) {
}

と指定すればOK

使う時は

showTooth(Cat::class.java) //ng
showTooth(Fox::class.java) //ok
showTooth(Dog::class.java) //ok
0
0
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
0
0