0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Kotlin】abstract classをinterface + 拡張関数で置き換える

0
Last updated at Posted at 2026-02-07

TL;DR

abstract class Foo {
    fun func(...) { ... }
}

interface Foo

fun Foo.func(...) { ... }

で置き換えられる。

状況想定

Kotlinには、classが継承可能なclassは1つという制約が有ります。
一方、複雑なクラスを実装する際は、複数のclassを継承させたいような場合も有ります。

このようなケースにおいて、対象に抽象プロパティと関数しか持たないようなクラスが含まれるなら、そのクラスをinterface + 拡張関数の形に置き換えることで、継承の制約を回避できます。

手法の意図

interfaceに関数実装を持たせたい場合、デフォルト実装にすることも考えられます。
ただ、デフォルト実装はoverride出来てしまうため、厳密に制約したい場合には不適です。

interface Foo {
    // funcはfinalに出来ない
    fun func(...) {...}
}

class FooImpl : Foo {
    // overrideできてしまう
    override fun func(...) { ... }
}

拡張関数であればoverride出来ないため、厳密な制約が実現できます。

関連記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?