-
Notifications
You must be signed in to change notification settings - Fork 0
/
LanguageFeatures.kt
69 lines (55 loc) · 1.95 KB
/
LanguageFeatures.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package org.example
// Sources:
// https://kotlinexpertise.com/kotlin-features-miss-java/
// https://android.jlelse.eu/kotlin-best-features-a3facac4d6fd
// Kotlin doesn't have new and semicolons are optional.
// see https://kotlinlang.org/api/latest/jvm/stdlib/
import kotlin.random.Random
// Single expression functions
fun trueOrFalse() = Random.nextBoolean()
// Default parameters
fun test(a: Int, printToConsole: Boolean = true) {
if (printToConsole) println("int a: " + a)
}
// Multiple method calls on a single instance
class Turtle {
fun penDown() { println("penDown") }
fun penUp() { println("penUp") }
fun turn(degrees: Double) { println("turn $degrees") }
fun forward(pixels: Double) { println("forward $pixels") }
}
// Extension functions
fun Int.multiplyBy5() = this * 5
fun String.greet(): String = this.plus(" we welcome you!")
// High order functions
fun addValue(f: (Int, Int) -> Int): Int = f(10, 20)
fun main(/*args: Array<String>*/) {
val a = 1
test(a, false)
test(2)
// Multiple method calls on a single instance
with(Turtle()) {
penDown()
for (i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
// Extension functions
println(50.multiplyBy5())
println("John".greet())
// High order functions
println(addValue { num1, num2 -> num1 * num2 }) // This will print 200
println(addValue { num1, num2 -> num1 - num2 }) // This will print -10
// By default all the object are null safe so they will not accept null as a value
// You need to explicitly define them by adding ? after its type.
var str1: String = "name"
// str1 = null // error: null can not be a value of a non-null type String
println(str1.length)
// see src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
@Suppress("VARIABLE_WITH_REDUNDANT_INITIALIZER")
var str2: String? = "name"
str2 = null
println(str2?.length)
}