Kotlinã®é¢æ°ã調ã¹ã¾ããã®ã§ããã®ã¾ã¨ãã
â»ä¸è¨URLã®ãµã¤ããåèã«ãã¾ãããè±èªãã¾ãã¯æè¡çãªç¥èãè³ãããå
容ã«èª¤ããå«ã¾ããããããããã¾ãã®ã§ããäºæ¿ãã ãã(´ï¼Ïï¼`)
ã¾ããè¼ãã¦ããã³ã¼ãä¾ã¯èªä½ã®ãã®ã§ãããåèãµã¤ãããå¼ç¨ãããã®ã§ã¯ããã¾ããã
â»æ¬ã¨ã³ããªã®8å²ã¯åèãµã¤ãã®ç¿»è¨³ã§ããæ®ãã®2å²ã¯ç§ã®è§£éã§å çãå¤æ´ãæ½ããæ§æã§ãã
åèãµã¤ãï¼http://confluence.jetbrains.net/display/Kotlin/Functions
追è¨ï¼2012-01-14 12:32ï¼
ã¤ã³ã©ã¤ã³é¢æ°ã«ã¤ãã¦è¿½è¨ãã¾ããã
åºæ¬
é¢æ°ã¯é常ã次ã®ããã«å®ç¾©ãã¾ãã
fun next(n : Int) : Int { return n + 1 }
funãã¼ã¯ã¼ãã«ç¶ãã¦ãé¢æ°ã®ååãå¼æ°ãæ»ãå¤ã®åãæå®ãã¾ãã
ä¸è¨ã®é¢æ°ã¯æ¬¡ã®ããã«ãè¨è¿°ã§ãã¾ãã
fun next(n : Int) = n + 1
ãã®å½¢ãSingle-expression functionã¨ãããããã§ããæ¥æ¬èªè¨³ãããªãåä¸å¼é¢æ°ã¨ãã§ãããã
åä¸å¼é¢æ°ã¯æ»ãå¤ã®åãçç¥ã§ãã¾ãã
Unitãè¿ãé¢æ°
é¢æ°ãæç¨ãªå¤ãä½ãè¿ããªãå ´åãé¢æ°ã®æ»ãå¤ã®åã¯Unitã¨ãªãã¾ãã
ï¼Unitã¯ã³ã³ãã¼ãã³ããæããªãã¿ãã«ã®åã§ããããã®ã¨ã¤ãªã¢ã¹ã¯Tuple0ã§ãããããå¯ä¸æã¤å¤ã¯()ã§è¨è¿°ããã¾ããã¿ãã«ã«ã¤ãã¦ã¯ã¾ãã®æ©ä¼ã«ï¼
fun sayHello() : Unit { println("Hello") }
ä¸è¨ã®é¢æ°ã¯ä»¥ä¸ã®ããã«ãæ¸ãæãããã¾ãã
fun sayHello() : Unit { println("Hello") return }
fun sayHello() : Unit { println("Hello") return () }
fun sayHello() { println("Hello") }
æå¾ã®ä¾ã®ããã«ãUnitãè¿ãé¢æ°ã¯ãæ»ãå¤ã®åãçç¥ã§ãã¾ãã
ãã¼ã«ã«é¢æ°
Kotlinã§ã¯ãé¢æ°å
ã«é¢æ°ãå®ç¾©ã§ãããã¼ã«ã«é¢æ°ããµãã¼ããã¦ãã¾ãã
ãã¼ã«ã«é¢æ°ããå¤å´ã®é¢æ°ã®ãã¼ã«ã«å¤æ°ãåç
§ãããã¨ãã§ãã¾ãã
ããã«ããã¼ã«ã«é¢æ°å
ã§returnãããã¨ãå¤å´ã®é¢æ°ã§ãreturnããã¾ãã
â¦æ¬¡ã®ã³ã¼ããèªãã§ããã ãã¨ãããããã¨æãã¾ãã
fun foo() : String { fun bar() : String { return@foo "AAA" } bar() return "BBB" }
ã¸ã§ããªãã¯é¢æ°
é¢æ°ã¯ã¸ã§ããªãã¯ãã©ã¡ã¼ã¿ãæã¤ãã¨ãã§ãã¾ãã
ã¸ã§ããªãã¯ãã©ã¡ã¼ã¿ã¯é¢æ°åã®å¾ã« <> âããããæ¬å¼§ã§æå®ãã¾ãã
å¯å¤é·å¼æ°
æå¾ã®å¼æ°ã«varargã¢ããã¼ã·ã§ã³ããã¼ã¯ãããã¨ã«ãããããã¯å¯å¤é·å¼æ°ã¨ãªãã¾ãã
fun sum(vararg ints : Int) : Int { var sum = 0 for(i in ints) { sum += i } return sum }
ããã©ã«ãå¼æ°
å¼æ°ã¯ããã©ã«ãå¤ãæã¤ãã¨ãã§ãã¾ããããã«ãããJavaããããªã¼ãã¼ãã¼ããããé¢æ°ã®æ°ãæ¸ãããã¨ãã§ãã¾ãã
fun sayHello(name : String = "Taro") { println("Hello, $name!") }
åä»ããããå¼æ°
ä¾ãã°ä¸è¨ã®é¢æ°ã¯æ¬¡ã®ããã«å¼ã³åºããã¨ãã§ãã¾ãã
fun main(args : Array<String>) { sayHello(name = "Android") }
å¼æ°ãå¤ãããã¤ããã©ã«ãå¤ãè¨å®ããã¦ããå ´åã«é常ã«ç°¡åã«é¢æ°ãå¼ã³åºããã¨ãå¯è½ã«ãªãã¾ãã
Infix calls
ã¡ã³ãé¢æ°ï¼ã¾ãã¯æ¡å¼µé¢æ°ï¼ã1ã¤ã ãå¼æ°ãåãå ´åãinfix formã§å¼ã³åºããã§ãã¾ãã
ã¤ã¾ããã¬ã·ã¼ãã®å¾ã®ãããã¨å¼æ°ã®åå¾ã®æ¬å¼§ãçç¥ã§ãã¾ãã
infix callã¯2ã¤ã®ãã©ã¡ã¼ã¿ãå¿
è¦ã¨ãã¾ãã
ä¾ãã°ãprint 1 㯠print ã®å·¦å´ã«ä½ããªãã®ã§ããã®å½¢ã¯è¨±ããã¾ããã
æ¡å¼µé¢æ°
æ¡å¼µé¢æ°(Extension function)ã¯ãã¬ã·ã¼ãã¨ãã¦åãæã£ãé¢æ°ãå®ç¾©ã§ããä»çµã¿ã§ãã
fun Int.isFizz() : Boolean = this % 3 == 0 fun main(args : Array<String>) { println(100.isFizz) }
é«æ¬¡é¢æ°
é«æ¬¡é¢æ°(Higher-order function)ã¯ãé¢æ°ãå¼æ°ã«åã£ãããé¢æ°ãè¿ãããããé¢æ°%E