-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTricks.kt
More file actions
71 lines (63 loc) · 1.86 KB
/
Copy pathTricks.kt
File metadata and controls
71 lines (63 loc) · 1.86 KB
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
70
71
package tutorial
import kotlin.system.measureNanoTime
fun main(args: Array<String>){
// Measuring code block execution time
var x = 0.0
val duration = measureNanoTime{
x = Math.pow(Math.E, 20.0)
}
println("Math.pow took $duration ns")
// Use backticks `` to define or use a keyword as function name
// This is mainly used to call
// a Java function that its name is (or will be) Kotlin keyword
fun `fun`() = println("my name is a keyword")
`fun`()
System.`in`.available() // Java function 'in' is reserved in Kotlin
}
/**
* Explosive Placeholders
* This is used to avoid syntax error
* because of unimplemented code
*/
fun connect(type: Boolean) : Int {
if (type) {
return 1
} else {
TODO("return something else ?")
}
}
/**
* Semantic Validation
* To avoid verbose 'if(not valid) throw exception' used in java
* Note than null checks are out of concern because of Kotlin's NullSafety
*/
fun calculate(a: Int, b: Int) : Int {
require(a > 0) {" a must be positive"}
require(b % 2 == 0) {" b must be even"}
return 0
}
/**
* Anything and Nothing
* All types (even Int) are extended from Any
* Nothing extends all types!
*/
fun printName(user : User?){
// User or its name maybe null, also throw returns Nothing
// so the type of name will be Nothing that extends (String, null, and Nothing)
val name = user?.name ?: throw IllegalArgumentException("User is null")
println("Name is $name.")
}
class User (val name : String?)
/**
* Anything and Nothing
* The return type 'Nothing' will tell compiler
* that no code can be accessed after calling this function
* thus writing a code after checkConnection() will show an error indication
* just like writing a code after 'return ...' or 'throw ...' does
* By removing Nothing, compiler cannot figure this out
*/
fun checkConnection() : Nothing {
while (true){
connect(true)
}
}