Last active
September 1, 2018 16:34
-
-
Save matey-jack/82b9c898727b43218b43ea859db6788f to your computer and use it in GitHub Desktop.
Four ways to define functions in Kotlin
This file contains 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 i_introduction._4_Lambdas | |
import org.junit.Assert | |
import org.junit.Test | |
class FunctionTest { | |
// C-style declared function with block body | |
fun inc_block(i: Int): Int { | |
return i + 1 | |
} | |
// declared function with expression body | |
fun inc(i: Int): Int = i + 1 | |
// inline function with expression body | |
val inc_var = { i: Int -> i + 1 } | |
// inline function with block body | |
// unlike Dart, this infers the return type | |
// (I checked this via hitting Ctrl+Q in IntelliJ IDEA.) | |
val inc_var_block = { i: Int -> | |
val result = i + 1 | |
result | |
// return keyword is actually forbidden in lambda-expressions | |
} | |
// but it's also easy to specify the type of a function-value variable: | |
val inc_var_explict: (Int) -> Int = inc_var_block | |
@Test | |
fun allTests() { | |
Assert.assertEquals(2, inc(1)) | |
Assert.assertEquals(2, inc_block(1)) | |
Assert.assertEquals(2, inc_var(1)) | |
Assert.assertEquals(2, inc_var_block(1)) | |
Assert.assertEquals(2, inc_var_explict(1)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment