1
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】interfaceにfinal funを定義する

1
Last updated at Posted at 2026-02-07

TL;DR

Kotlinの仕様として不可能だが、拡張関数として実装すれば同様の状態は実現できる。

interface Foo

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

状況

interfaceのデフォルト実装はfinalに出来ず、常にoverride可能です。

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

class FooImpl : Foo {
    override fun func(...) { ... }
}

final化したい場合は、冒頭で紹介したように、拡張関数として定義することで実現できます。

以下のような実装に役立ちます。

補足

Kotlinの元プロジェクトリーダーであるRoman Elizarov氏は「It is exactly how "final fun in interface" are supposed to be represented in Kotlin by design.」と回答しています。

少なくとも、2018年時点ではこれが推奨される手法だったと言えるでしょう。

1
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
1
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?