Skip to content

Commit d8b262a

Browse files
committed
[Kotlin] added type aliases, inline classes, delegation, delegated properties, singleton, functions
1 parent 984757a commit d8b262a

23 files changed

+1258
-142
lines changed

KotlinFromScratch/.idea/kotlinc.xml

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

KotlinFromScratch/.idea/workspace.xml

+250-126
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import kotlin.properties.Delegates
2+
import kotlin.reflect.KProperty
3+
4+
class DelegatedProperties {
5+
fun test() {
6+
println("Standard delegates - Lazy")
7+
val lazyValue: String by lazy {
8+
println("computed")
9+
"Hello"
10+
}
11+
println("Call lazy value at the first time: $lazyValue")
12+
println("Call lazy value again: $lazyValue")
13+
14+
// skip Lazy, read more in singleton_kotlin/
15+
println("")
16+
println("Observable")
17+
val user = User()
18+
user.name = "first"
19+
user.name = "second"
20+
21+
22+
println("")
23+
println("Storing Properties in a Map")
24+
val classmate = Classmate(
25+
mapOf(
26+
"name" to "John Doe",
27+
"age" to 25
28+
)
29+
)
30+
println("name: ${classmate.name}, age: ${classmate.age}")
31+
println("")
32+
println("Storing Properties in a mutable map")
33+
val mutableClasses = MutableClassmate(
34+
mutableMapOf(
35+
"name" to "John Doe",
36+
"age" to 25
37+
)
38+
)
39+
mutableClasses.age = 29
40+
println("name: ${mutableClasses.name}, age: ${mutableClasses.age}")
41+
42+
43+
println("")
44+
println("Implement properties including standard delegates once for all")
45+
val e = Example()
46+
println(e.p)
47+
e.p = "new"
48+
49+
50+
println("")
51+
println("Local delegated properties")
52+
f {Foo()}
53+
54+
}
55+
56+
private fun f(computeFoo: () -> Foo) {
57+
val memorizedFoo by lazy(computeFoo)
58+
if (memorizedFoo.isValid()) {
59+
memorizedFoo.doSomething()
60+
}
61+
}
62+
63+
class Example {
64+
var p: String by Delegate()
65+
}
66+
67+
class Delegate {
68+
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
69+
return "$thisRef, thank you for delegating '${property.name}' to me!"
70+
}
71+
72+
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
73+
println("'$value' has been assigned to '${property.name}' in $thisRef.")
74+
}
75+
}
76+
77+
class User {
78+
var name: String by Delegates.observable("<no name>") { _, oldValue, newValue ->
79+
println("$oldValue -> $newValue")
80+
}
81+
}
82+
83+
class Classmate(map: Map<String, Any?>) {
84+
val name: String by map
85+
val age: Int by map
86+
}
87+
88+
class MutableClassmate(map: MutableMap<String, Any?>) {
89+
var name: String by map
90+
var age: Int by map
91+
}
92+
93+
class Foo {
94+
fun isValid(): Boolean = true
95+
fun doSomething() = println("Do something")
96+
}
97+
}

KotlinFromScratch/src/Delegation.kt

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Delegation {
2+
3+
fun test() {
4+
println("Implementation by delegation")
5+
val baseImpl = BaseImpl(10)
6+
Derived(baseImpl).println() // message from BaseImpl, if you want to show message from Derived, override println()
7+
Derived(baseImpl).print()
8+
println(Derived(baseImpl).message) // message from Derived
9+
}
10+
11+
interface Base {
12+
val message: String
13+
fun print()
14+
fun println()
15+
}
16+
17+
class BaseImpl(x: Int) : Base {
18+
override val message = "BaseImpl: x = $x"
19+
20+
override fun print() {
21+
print(message)
22+
}
23+
24+
override fun println() {
25+
println(message)
26+
}
27+
}
28+
29+
// The last "b" (from ": Base by b") is implemented by the "b" in "Derived(b: Base)"
30+
class Derived(b: Base) : Base by b {
31+
32+
override val message = "Message of Derived"
33+
// overriding functions is optional
34+
override fun print() {
35+
print("Derived\n")
36+
}
37+
38+
// override println() or println the message from BaseImpl
39+
// override fun println() {
40+
// println(message)
41+
// }
42+
}
43+
}

KotlinFromScratch/src/EnumClasses.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class EnumClasses {
3030

3131
enum class RGB { RED, GREEN, BLUE }
3232

33-
inline fun <reified T : Enum<T>> printAllValues() {
33+
private inline fun <reified T : Enum<T>> printAllValues() {
3434
print(enumValues<T>().joinToString { it.name })
3535
}
3636

KotlinFromScratch/src/Functions.kt

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
class Functions {
2+
fun test() {
3+
println("Basic functions")
4+
println(double(10))
5+
println(triple(10))
6+
println(isPrimeNumber(17))
7+
8+
println("")
9+
println("Default arguments")
10+
val s = "Function parameters can have default values, which are"
11+
read(s.toByteArray())
12+
13+
println("")
14+
println("Override functions")
15+
val b = B()
16+
b.foo()
17+
18+
println("")
19+
println("lambda")
20+
foo(0, 2) { println("Fill in all arguments") }
21+
foo(0) { println("Fill in some arguments") }
22+
foo(baz = 2) { println("Fill in specific arguments") }
23+
foo(qux = { println("Fill in the last argument") })
24+
foo { println("Fill in the last argument") }
25+
26+
27+
println("")
28+
println("variable number of arguments (vararg)")
29+
foo(strings = *arrayOf("a", "b", "c"))
30+
31+
println("")
32+
println("Unit-returning functions")
33+
println("fun bar(): Unit {} is equivalent to fun bar() {}")
34+
35+
36+
println("")
37+
println("infix functions")
38+
println("aaa".add(3))
39+
println("aaa" add 3)
40+
this bar "bbb"
41+
bar("bbb")
42+
43+
println("")
44+
println("Local functions")
45+
f()
46+
}
47+
48+
private fun double(x: Int): Int = 2 * x
49+
private fun triple(x: Int) = 3 * x
50+
private fun isPrimeNumber(x: Int): Boolean {
51+
var factors = 0
52+
for (i in 2..x / 2) {
53+
if (x % i == 0) {
54+
factors++
55+
}
56+
}
57+
return factors == 0
58+
}
59+
60+
private fun read(bytes: ByteArray, off: Int = 0, len: Int = bytes.size) {
61+
val s = String(bytes, off, len)
62+
println(s)
63+
}
64+
65+
open class A {
66+
open fun foo() {}
67+
}
68+
69+
class B : A() {
70+
override fun foo() {}
71+
}
72+
73+
private fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) {
74+
qux()
75+
}
76+
77+
// In Java -> public void println(String.. args) { }
78+
private fun foo(vararg strings: String) {
79+
println(strings[0])
80+
}
81+
82+
private infix fun String.add(x: Int) = "$this$x"
83+
private infix fun bar(s: String) = println(s)
84+
85+
private fun f() {
86+
fun f() {
87+
println("call f() in f()")
88+
}
89+
print("call f() -> ")
90+
f()
91+
}
92+
}

KotlinFromScratch/src/InlineClass.kt

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// since Kotlin 1.3, it is impossible to call functions which accept inline classes from Java.
2+
class InlineClass {
3+
4+
fun test() {
5+
println("Inline Classes")
6+
val martin = Name("Martin")
7+
martin.greet()
8+
println(martin.length)
9+
10+
println("")
11+
println("Representation")
12+
asInline(martin)
13+
asGeneric(martin)
14+
asInterface(martin)
15+
asNullable(martin)
16+
println(id(martin))
17+
18+
println("")
19+
println("Inline classes vs type aliases")
20+
val nameAlias: NameTypeAlias = ""
21+
val nameInlineClass: NameInlineClass = NameInlineClass("")
22+
val s: String = ""
23+
24+
acceptString(nameAlias)
25+
// acceptString(nameInlineClass) // not allow
26+
27+
acceptNameTypeAlias(s)
28+
// acceptNameInlineClass(s) // not allow
29+
30+
}
31+
32+
private fun asInline(n: Name) {}
33+
private fun <T> asGeneric(t: T) {}
34+
private fun asInterface(i: I) {}
35+
private fun asNullable(n: Name?) {}
36+
private fun <T> id(t: T): T = t
37+
38+
private fun acceptString(s: String) {}
39+
private fun acceptNameTypeAlias(n: NameTypeAlias) {}
40+
private fun acceptNameInlineClass(n: NameInlineClass) {}
41+
}
42+
43+
interface I
44+
45+
inline class Name(private val s: String) : I {
46+
val length: Int
47+
get() = s.length
48+
49+
fun greet() {
50+
println("Hello, $s")
51+
}
52+
}
53+
54+
inline class NameInlineClass(val s: String)
55+
typealias NameTypeAlias = String

0 commit comments

Comments
 (0)