Created
September 13, 2022 10:00
-
-
Save emelent/99309d95b3ae480951efc83613a4807d to your computer and use it in GitHub Desktop.
Kotlin interfaces and operator overloading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Donkey { | |
fun speak(speech: String) | |
} | |
fun interface ISpeechDevice { | |
operator fun invoke(speech: String) | |
} | |
class PrintDevice: ISpeechDevice { | |
override fun invoke(speech: String) { | |
println(speech) | |
} | |
} | |
class TextFileDevice: ISpeechDevice { | |
override fun invoke(speech: String) { | |
println("Writing '$speech' to some file...") | |
} | |
} | |
class RealDonkey(private val device: ISpeechDevice) : Donkey { | |
override fun speak(speech: String) { | |
device(speech) | |
} | |
} | |
class Person( | |
val name: String, | |
val age: Int | |
) { | |
operator fun plus(p2: Person): Person { | |
return Person( | |
name = name + p2.name, | |
age = age + p2.age | |
) | |
} | |
operator fun plus(i: Int): Person { | |
return Person( | |
name = name, | |
age = age + i | |
) | |
} | |
fun intro() { | |
println("Hi I'm $name and I'm $age years old.") | |
} | |
} | |
fun people() { | |
val p1 = Person("Jake", 20) | |
val p2 = Person("Simon", 30) | |
p1.intro() // Jake 20 | |
p2.intro() // Simon 30 | |
(p1 + 10).intro() // Jake 30 | |
(p1 + p2).intro() // JakeSimon 50 | |
} | |
fun speakingDevices() { | |
val pDevice = PrintDevice() | |
val tDevice = TextFileDevice() | |
val d1 = RealDonkey(pDevice) | |
val d2 = RealDonkey(tDevice) | |
val d3 = RealDonkey{ | |
println("THe magic device says: $it") | |
} | |
} | |
fun main() { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment