Skip to content

Instantly share code, notes, and snippets.

@yyYank
Created September 6, 2015 06:54
Show Gist options
  • Save yyYank/6fb0276df0ea464251ef to your computer and use it in GitHub Desktop.
Save yyYank/6fb0276df0ea464251ef to your computer and use it in GitHub Desktop.
Tupleからのhttps://sites.google.com/site/tarokotlin/chap5/sec52 パターンマッチ変更を考える
fun main(args : Array<String>) {
// コード5.2.2 タプルの各要素の型や値でパターンマッチング
val pair1 = Pair(1, 2)
when(pair1) {
//できない is #(0, 0) -> "(0, 0)"
// できない is #(0, Int) -> "(0, Int)"
// できない is #(Int, 0) -> "(Int, 0)"
is Pair<Int, Int> -> "(Int, Int)" // コンパイルレベルで自明
// コンパイルエラー is Pair<String, String> -> "(String, String)"
else -> "unknown"
}
// コード5.2.3 バインディングパターンの簡単な例
val pair2 : Pair<String, Int> = Pair("taro", 23)
if(pair2 is Pair<String, Int>) {
println("${pair2.first} (${pair2.second})") // taro (23)
}
// コード5.2.4 強力なバインディングパターン
val pair3 = Pair(1,2)
when(pair3) {
// できない is #(val a in 0..10, val b in 0..10) -> // なんかしらの
// できない is #(val a is Int, val b is Int) -> // 式やら
// できない is #(val a, val b) -> // 処理やら
}
if(pair3.first in 0..10 && pair3.second in 0..10){
// なんかしらの
} else if(pair3.first is Int && pair3.second is Int){
// 式やら
} else {
// 処理やら
}
}
@ngsw-taro
Copy link

こういうのもある。便利。

val pair2 : Pair<String, Int> = Pair("taro", 23)
val (name: String, age: Int) = pair2
// val (name, age) = pair2 // もちろん型は省略できる

println(name) // => taro
println(age)  // => 23

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment