LoginSignup
11
17

More than 5 years have passed since last update.

kotlinでのラムダ式・メソッド渡し

Last updated at Posted at 2015-07-24

書き方のサンプルがとても少ないのでメモ
ラムダ式の書き方は{}とfunの2種類あり、用途に応じて使い分ける必要が有る、気をつけろ!

参考URL

いろいろなパターン

hoge.kt

//戻り値が無い場合はvoidじゃなくてUnit
fun hoge(method1:()->Unit,
         method2:(String,String)->String) : ()->Unit
{
    //使い方
    method1()
    val str = method2("aaa","cccc")

    //メソッド内での定義、funを使う
    val method3 = fun(n: Int) :Int { return n * 2 }
    val method4 = fun(){print("Hello どうも 僕はここにいる")}

    //メソッド内での定義、{でも良い、でもその場合は型を指定しておく必要が有る}
    val method5:(String,String)->String =  {s1,s2 -> "hoge"}

    //メソッドにメソッドを渡す、書き方は2通り
    val method6 = hoge(
            {->print("Hello どうも 僕はここにいる")},
            {s1,s2 -> "hoge"})

    val method7 = hoge(
            fun(){print("Hello どうも 僕はここにいる")},
            fun(s1:String, s2:String) :String { return "hoge" })
    return method4
}
11
17
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
17