LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin1.7.0: 型引数のアンダースコア演算子とは?

Posted at

はじめに

Kotlin1.7.0が6月7日にリリースされましたが、リリース内容の中に型引数にアンダースコア演算子が導入されたとの記載があります。
これについて理解を深めるために簡単にまとめておこうと思います。

型引数のアンダースコア演算子とは?

公式には以下実装を例に解説が載っています。

abstract class SomeClass<T> {
    abstract fun execute(): T
}

class SomeImplementation : SomeClass<String>() {
    override fun execute(): String = "Test"
}

class OtherImplementation : SomeClass<Int>() {
    override fun execute(): Int = 42
}

object Runner {
    inline fun <reified S: SomeClass<T>, T> run(): T {
        return S::class.java.getDeclaredConstructor().newInstance().execute()
    }
}

fun main() {
    // TはSomeImplementationがSomeClass<String>から継承されているため、Stringと推論される
    val s = Runner.run<SomeImplementation, _>()
    assert(s == "Test")

    // TはOtherImplementationがSomeClass<Int>から継承されいているため、Intと推論される
    val n = Runner.run<OtherImplementation, _>()
    assert(n == 42)
}

アンダースコア演算子は、現状だと使ってない引数等に警告が出て、警告に則り修正すると、_に変換されるアレですね。
それが今回の対応で少し便利になり、元の親クラスで指定されている型までちゃんと推測してくれるようになったようです。

推測してくれる点は便利だと感じましたが、そこまで利便性が跳ね上がるような対応ではない認識ですね。
ジェネリックを多用している汎用的な機能に関しては、多少便利かなといった印象です。

さいごに

kotlinもアップデートを重ね、もう1.7なのですね。
言語も日々進化し続けているので、私も最新から遅れないよう、こういった新しい機能にはなるべく目を通しておこうと思います。

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