1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlin のパターンマッチを使ったメソッドで型パラメータをいい感じに扱って欲しい

Posted at

Kotlin で

sealed class Query<T>
object StringQuery : Query<String>()
object IntQuery : Query<Int>()

みたいなシールドクラスがあったとして、

fun <T> executeQuery(query: Query<T>): T = when (query) {
  is StringQuery -> "何か文字列"
  is IntQuery -> 1000
}

という感じで型に応じた返り値を返したいのだけど、上のようなコードを書くと 「Type Mismatch. Required: T / Found: String」 みたいな感じでコンパイラに怒られる。

こういう感じのことをするいい方法ってないものだろうか…… :thinking:

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?