Created
May 2, 2017 16:14
-
-
Save ice1000/c024efa6d46ef63111c95dee139a83e7 to your computer and use it in GitHub Desktop.
Kotlin can also write recursive lambda
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/** | |
* Created by ice1000 on 2017/5/2. | |
* | |
* @author ice1000 | |
*/ | |
fun main(args: Array<String>) { | |
fun lambda(it: Int): Int = | |
if (it <= 2) 1 else lambda(it - 1) + lambda(it - 2) | |
(1..10) | |
.map(::lambda) | |
.forEach(::println) | |
var lambda2: (Int) -> Int = { it } | |
lambda2 = { if (it <= 2) 1 else lambda(it - 1) + lambda(it - 2) } | |
(1..10) | |
.map(lambda2) | |
.forEach(::println) | |
} | |
Oh, it was written long ago and there weren't local lateinit back then. Thanks for the suggestion!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your
lambda2
is not recursive, it callslambda
by mistake.You can make it recursive using
lateinit
: