+48
Kotlin/Functions.org
+48
Kotlin/Functions.org
···
1
+
* Functions
2
+
3
+
To make your code more concise, you can use single-expression functions.
4
+
For example, the =sum()= function can be shortened
5
+
6
+
#+begin_src kotlin
7
+
fun sum(x: Int, y: Int): Int {
8
+
return x + y
9
+
}
10
+
11
+
println(sum(1,2))
12
+
#+end_src
13
+
14
+
#+RESULTS:
15
+
: 3
16
+
17
+
#+begin_src kotlin
18
+
fun sum2(x: Int, y: Int) = x + y
19
+
20
+
println(sum2(1,2))
21
+
#+end_src
22
+
23
+
#+RESULTS:
24
+
: 3
25
+
26
+
** Lambda expressions
27
+
28
+
You can even write lambda expressions in kotlin
29
+
30
+
#+begin_src kotlin
31
+
fun uppercaseString(string: String): String {
32
+
return string.uppercase()
33
+
}
34
+
35
+
println(uppercaseString("hello"))
36
+
#+end_src
37
+
38
+
#+RESULTS:
39
+
: HELLO
40
+
41
+
Can also be written to:
42
+
43
+
#+begin_src kotlin
44
+
println({ string: String -> string.uppercase() }("hello"))
45
+
#+end_src
46
+
47
+
#+RESULTS:
48
+
: HELLO