Created
September 6, 2015 06:54
-
-
Save yyYank/6fb0276df0ea464251ef to your computer and use it in GitHub Desktop.
Tupleからのhttps://sites.google.com/site/tarokotlin/chap5/sec52 パターンマッチ変更を考える
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
// 処理やら | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
こういうのもある。便利。