iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

【Kotlin】複数の型を返したい

〇〇の処理をした時に、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なりで自作する必要があるそうです。PairTripledata 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)"
}

てな感じで本日も以上となります🍺

参考

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com