LoginSignup
10
13

More than 5 years have passed since last update.

Kotlinコードでシンプルなコンストラクタ

Posted at

書いていたコード

CustomViewを実装する際にコンストラクタをたくさん書いておりました。すっきりまとめる場合には@JvmOverloadsを使えばいいことを知りました。

今までこんな風に書いていました。

class PickerView: View {
    constructor(context: Context) : this(context, null) {
        prepare()
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        prepare()
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        prepare()
    }

    fun prepare() {
    }
}

@JvmOverloadsアノテーションを使う

@JvmOverloadsを使うとすっきりできますね!

class PickerView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    init {
        prepare()
    }

    fun prepare() {
    }
}

他のものもすっきり書けそうでした。

class PickerViewPager : ViewPager {
    @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : super(context, attrs)
}

参考にさせていただきました!!
http://qiita.com/jmatsu/items/6c141ba0acb13409c7bf

10
13
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
10
13