-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBaseClass.kt
131 lines (99 loc) · 2.54 KB
/
BaseClass.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import package1.BaseClassExtensions
class BaseClass {
fun test() {
println("BaseClass functions")
val l = mutableListOf(1, 2, 3)
l.swap(1, 2)
println(l)
hello()
foo() // member always win
println("")
println("Call extension functions of this class declared other class")
val plugin = BaseClassExtensions()
plugin.caller(this)
println("")
println("Extension properties")
println(name)
println("")
println("Common extensions")
val a: String? = null
println(a.toString())
val list = List(5) { i -> i * i }
println(list)
println("")
println("Companion Objects")
val e = E.newInstance() // val e = E() is not allowed here
println(E.INNER_CONSTANT)
println(F.INNER_CONSTANT)
println("")
println("Complicated scenarios")
val paper = Paper()
val sketchbook = Sketchbook()
paper.caller(Node())
paper.caller(BlackNode())
sketchbook.caller(Node())
sketchbook.caller(BlackNode())
}
private fun foo() {
println("member foo()")
}
override fun toString(): String {
return "toString() from BaseClass"
}
}
// Nullable receiver
fun Any?.toString(): String {
if (this == null) return "null"
return toString()
}
// extension functions
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
fun BaseClass.hello() {
println("Hello")
}
fun BaseClass.foo() {
println("Extension foo()")
}
// extension properties
val BaseClass.name: String
get() = "Extension name"
class E private constructor() {
companion object {
const val INNER_CONSTANT = "E"
fun newInstance() = E()
}
}
class F {
companion object CompanionName {
const val INNER_CONSTANT = "F"
}
}
open class Node
class BlackNode : Node()
open class Paper {
open fun Node.draw() {
println("Draw a node on Paper")
}
open fun BlackNode.draw() {
println("Draw a black node on Paper")
}
fun caller(node: Node) {
node.draw()
}
// without this, BlackNode.draw() will never be called
fun caller(node: BlackNode) {
node.draw()
}
}
class Sketchbook : Paper() {
override fun Node.draw() {
println("Draw a node in Sketchbook")
}
override fun BlackNode.draw() {
println("Draw a black node in Sketchbook")
}
}