〇〇の処理をした時に、AとBの異なる型の値を返したい!という時ありますよね。Swiftでは下記のように、シンプルにタプルで返せば良かったのですが、Kotlinではこの書き方ができなかったのでメモしておきます👷♀️
func hoge() -> (Int, String) { return (1, "a") }
結論
Kotlinでは、Pair
型を使用することで、複数の型の値を返すことができるそうです✍️
fun hoge(): Pair<Int, String> { return Pair(1, "a") }
また、3つの値を返す場合はTriple
を使います。
fun hoge(): Triple<Int, String, String> { return Triple(1, "a", "b") }
ちなみに、4つ以上になる場合は、対応している型は存在しないため、data class
なりで自作する必要があるそうです。Pair
・Triple
もdata class
で作られてますね👀
public data class Triple<out A, out B, out C>( public val first: A, public val second: B, public val third: C ) : Serializable { /** * Returns string representation of the [Triple] including its [first], [second] and [third] values. */ public override fun toString(): String = "($first, $second, $third)" }
てな感じで本日も以上となります🍺
参考
- https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-pair/
- https://qiita.com/sdkei/items/2d5dab51b53975286945#fn2