Skip to content

Instantly share code, notes, and snippets.

@matey-jack
Last active September 1, 2018 16:34
Show Gist options
  • Save matey-jack/82b9c898727b43218b43ea859db6788f to your computer and use it in GitHub Desktop.
Save matey-jack/82b9c898727b43218b43ea859db6788f to your computer and use it in GitHub Desktop.
Four ways to define functions in Kotlin
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