Skip to content

Instantly share code, notes, and snippets.

@ToshihitoKon
Last active May 16, 2018 05:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToshihitoKon/a327a43a2cf0b84d63c7bbd35d720c49 to your computer and use it in GitHub Desktop.
Save ToshihitoKon/a327a43a2cf0b84d63c7bbd35d720c49 to your computer and use it in GitHub Desktop.
Kotlinの構文わからなくなるのでメモ
// #関数定義
// fun [関数名] ( [引数名1]:[型], [引数名2]:[型] ... ): [返り値型] { [式] }
fun addOne(num: Int): Int {
num+1
}
// fun [関数名] ( [引数名1]:[型], [引数名2]:[型] ... ): [返り値型] = { [式] }
fun addOne(num: Int): Int = num+1
// 返り値の型が自明な場合は省略可(可読性下がるため非推奨)
fun addOne(num: Int) = num+1
// 可変長引数(関数1つにつき一つのみ指定可)
// 引数名の前にvarargを付ける
fun sum(vararg ints: Int): Int {
var sum=0
for(i in ints)
s += i
return sum
}
// 可変長引数を渡す例
sum(1, 2, 3)
sum( *intArrayOf(1, 2, 3) ) // *をつけると 配列を展開して可変長引数として渡せる
// 可変長引数と通常の引数を同時に使うときは、引数名を指定してあげると上手くいくらしい
// 関数型の定義
// ( [引数の型] ) -> [返り値の型]
val func: (Int)->int = ::addOne // addOne関数オブジェクトを代入
// 高階関数(引数に関数オブジェクトを受け取る,関数オブジェクトを返す)
fun strProc( str: String func: (String)->String ): String {
return func(str)
}
// ラムダ式
val func: (String)->String = { str: String -> "Hello,${str}" }
// 型省略(どちらでもOK)
val func = { str: String -> "Hello,${str}" }
val func: (String)->String = { str -> "Hello,${str}" }
// ラムダ式の引数が1つの場合、itでその引数を指す
val func: (String)->String = { "Hello,${it}" }
// 高階関数に関数オブジェクトを渡す
strProc("Kotlin", func)
// *** sample ***
// func{1..4}はすべて同じ
val func1: (String)->String = { str: String -> "Hello,${str}" } // 省略なし
val func2 = { str: String -> "Hello,${str}" } // 宣言時の型を省略
val func3: (String)->String = { str -> "Hello,${str}" } // ラムダ式内の型を省略
val func4: (String)->String = { "Hello,${it}" } // ラムダ式内で暗黙の変数itを利用
fun strProc(str: String, func: (String)->String): String{ return func(str) }
// 出力はすべて同じ
fun main(args: Array<String>){
println( strProc("Kotlin", func1) )
println( strProc("Kotlin", func2) )
println( strProc("Kotlin", func3) )
println( strProc("Kotlin", func4) )
println( strProc("Kotlin", { "Hello,${it}" }) ) // setProcに直接ラムダ式で関数オブジェクトを渡す
println( strProc("Kotlin") { "Hello,${it}" } ) // 糖衣構文(引数の最後が関数型の場合に外に出せる)
}
// *** sample_end ***
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment