Skip to content

Instantly share code, notes, and snippets.

@daneko

daneko/1.kt Secret

Last active December 20, 2015 01:19
blog memo
fun sayHello(target : String) {
println("Hello, $target!")
}
val target : Any = "world"
if(target is String) {
sayHello(target) // Hello, world!
}
def sayHello(target : String) = println(s"Hello, $target!")
val target : Any = "world"
target match {
case x:String => sayHello(x)
case _ =>
}
fun isUpperCase(str : String) : Boolean {
fun String.all(f : (Char) -> Boolean) : Boolean {
for(val c in this) {
if(!f(c)) {
return false
}
}
return true
}
return str.all {
Character.isUpperCase(it)
}
}
def isUpperCase(str : String) : Boolean = {
implicit class MyRichString(val self : String) {
def all(f : Char => Boolean) : Boolean = self.forall(f)
}
str.all(Character.isUpperCase)
}
fun run(f : () -> Unit) = f()
// リテラルじゃないから引数として渡せないらしい
//fun sayHello() {
// println("Hello")
//}
val sayHello = {
println("Hello")
}
run(sayHello)
def run(f: () => Unit ) = f()
val runLiteral = (f:() => Unit) => f()
def sayHelloFunc() = println("Func!!")
val sayHelloLiteral = () => println("Literal!!")
run( sayHelloFunc )
run( sayHelloLiteral )
runLiteral( sayHelloFunc )
runLiteral( sayHelloLiteral )
when(pair) {
is #(0, 0) -> "(0, 0)"
is #(0, Int) -> "(0, Int)"
is #(Int, 0) -> "(Int, 0)"
is #(Int, Int) -> "(Int, Int)"
is #(String, String) -> "(String, String)"
else -> "unknown"
}
val pair:(Any, Any) = ...
pair match {
case (0, 0) => "(0, 0)"
case (0, _:Int) => "(0, Int)"
case (_:Int, 0) => "(Int, 0)"
case (_:Int, _:Int) => "(Int, Int)"
case (_:String, _:String) => "(String, String)"
case _ => "unknown"
}
val pair : #(String, Int) = #("taro", 23) // ← 先日25歳になっていたような…w
if(pair is #(val a, val b)) {
println("$a ($b)") // taro (23)
}
val pair = ("taro", 23)
// スマートキャストとおんなじような事やるならパターンマッチも使えばいいかな
val (a, b) = pair
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment