Skip to content

Commit a838bfb

Browse files
author
Alexander Rogalskiy
committed
Updates on files
1 parent 0c01fe4 commit a838bfb

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package io.nullables.api.playground.patterns.delegation2
2+
3+
interface Engine {
4+
fun printEngine()
5+
}
6+
7+
class Diesel(val power: Int) : Engine {
8+
override fun printEngine() {
9+
println("Diesel $power")
10+
}
11+
}
12+
13+
class Car(e: Engine) : Engine by e
14+
15+
fun main(args: Array<String>) {
16+
val engine = Diesel(10)
17+
Car(engine).printEngine()
18+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package io.nullables.api.playground.patterns.delegation3;
2+
3+
import kotlin.lazy
4+
import kotlin.properties.Delegates
5+
import kotlin.reflect.KProperty
6+
7+
class EngineDelegate {
8+
private val speedLimit : Int = 5
9+
10+
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
11+
return if (thisRef is HybridCar && thisRef.speed < speedLimit) "Electric" else "Gas"
12+
}
13+
14+
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
15+
println("$value has been manually set to '${property.name}' in $thisRef.")
16+
}
17+
}
18+
19+
class HybridCar(var speed : Int) {
20+
var engine: String by EngineDelegate()
21+
}
22+
23+
class LazyCar {
24+
val engine: String by lazy {
25+
println("computed!")
26+
"Gas"
27+
}
28+
}
29+
30+
class SmartCar {
31+
var speed : Int by Delegates.observable(10, {
32+
prop, old, new -> println("Changed from $old to $new")
33+
})
34+
}
35+
36+
class SerializedCar (val map: Map<String, Any?>) {
37+
val speed : Int by map
38+
val engine : String by map
39+
}
40+
41+
fun main(args: Array<String>) {
42+
val car = HybridCar(10)
43+
println(car.engine) // output: Gas
44+
car.speed = 2
45+
println(car.engine) // output: Electric
46+
47+
val smartCar = SmartCar()
48+
smartCar.speed = 10;
49+
smartCar.speed++
50+
51+
val map = HashMap<String, Any?>()
52+
map.put("speed", 10)
53+
map.put("engine", "Gas")
54+
var serializedCar = SerializedCar(map)
55+
println("Car with engine ${serializedCar.engine} and speed ${serializedCar.speed}")
56+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package io.nullables.api.playground.patterns.extension
2+
3+
open class Office(var space : Int)
4+
5+
fun Office.hasTable() = true
6+
7+
fun Office.plus(right : Office) : Office {
8+
return Office(this.space + right.space)
9+
}
10+
11+
fun main(args: Array<String>) {
12+
val myOffice = Office(1)
13+
println("Office has table ${myOffice.hasTable()}") // output: Office has table yes
14+
}

0 commit comments

Comments
 (0)