Skip to content

Instantly share code, notes, and snippets.

@lgzh1215
Last active September 8, 2017 03:13
Show Gist options
  • Save lgzh1215/bbd0fee6815d9a3446273fd0b340ea20 to your computer and use it in GitHub Desktop.
Save lgzh1215/bbd0fee6815d9a3446273fd0b340ea20 to your computer and use it in GitHub Desktop.
Kotlin劝退流
fun main(vararg args: String) {
val str = "4"
var i = 0
switch(str) {
case("5") { i++; println("case(\"5\")"); 打断() }
case("4") { i++; println("case(\"4\")") }
case("3") { i++; println("case(\"3\")") }
case("2") { i++; println("case(\"2\")"); 打断() }
case("1") { i++; println("case(\"1\")") }
}
println("i = $i")
// 输出:
//
// case("4")
// case("3")
// case("2")
// i = 3
}
fun switch(any: Any?, build: CaseBuilder.() -> Unit) = CaseBuilder(any).build()
@DslMarker annotation class Switch
@Switch class CaseBuilder(val left: Any?) {
private var match: BooleanArray = booleanArrayOf(false)
@Switch class Case(private val match: BooleanArray) {
fun 打断() {
match[0] = false
}
}
fun case(right: Any?, block: Case.() -> Unit) {
if (left == right) match[0] = true
if (match[0]) block(Case(match))
}
}
typealias 布尔类型 = Boolean
fun main(vararg args: String) {
val 返回值: String = ("42" == "真理") 问号 "是的,我看过《银河系漫游指南》" 冒号 "瞎扯啥"
println(返回值) // 瞎扯啥
}
class 三块钱表达式<out 任意类型>(val 布尔值: 布尔类型, val 真值: 任意类型)
infix fun <任意类型> 布尔类型.问号(真值: 任意类型) = 三块钱表达式(this, 真值)
infix fun <任意类型一, 任意类型二, 任意类型三> 三块钱表达式<任意类型一>.冒号(假值: 任意类型二)
where 任意类型一 : 任意类型三, 任意类型二 : 任意类型三 = if (布尔值) 真值 else 假值
@mcxinyu
Copy link

mcxinyu commented Sep 8, 2017

你这个 switch 是 java 实现,kotlin 的 when 怎么办?

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