Last active
August 5, 2024 23:52
-
-
Save BolajiOlajide/7c9a58f34111df6961653a92f2c7d4bd to your computer and use it in GitHub Desktop.
OOP in Kotlin
This file contains hidden or 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
/** | |
* You can edit, run, and share this code. | |
* play.kotlinlang.org | |
*/ | |
fun main() { | |
val myCar = Car() | |
println(myCar.color) | |
println(myCar.model) | |
myCar.drive() | |
val myFunnyCar = FunnyCar( | |
color = "Green" | |
//model = "GLE" | |
) | |
println(myFunnyCar.color) | |
println(myFunnyCar.model) | |
val myTruck = Truck( | |
color = "Magenta", | |
model = "AMG" | |
) | |
myTruck.speed(100, 199) | |
println(myTruck.color) | |
println(myTruck.model) | |
myTruck.drive() | |
val btn = CustomButton(label = "Submit") | |
btn.onClick(message = "clicking...") | |
// extension functions | |
println("Hello".bolaji(", World")) | |
println("Hello".removeFirstAndLastChars()) | |
val person = Person( | |
name = "Joe", | |
lastName = "Ball", | |
age = 23 | |
) | |
println(person) | |
} | |
data class Person( | |
val name: String, | |
val lastName: String, | |
val age: Int | |
) | |
// This extends the base string class to include | |
// custom functions beyond what the kotlin language | |
// gives us | |
fun String.bolaji(toAppend: String): String { | |
return this.plus(toAppend) | |
} | |
fun String.removeFirstAndLastChars(): String = this.substring(1, this.length - 1) | |
interface Clickable { | |
fun onClick(message: String) | |
} | |
class CustomButton(val label: String): Clickable { | |
override fun onClick(message: String) { | |
println("button with label '$label' was clicked with message '$message'") | |
} | |
} | |
class Car { | |
// immutable | |
val color: String = "Red" | |
val model: String = "XMD" | |
// mutable | |
var isDriving: Boolean = false | |
fun drive() { | |
this.isDriving = true | |
println("Driving .... vrooom!") | |
} | |
} | |
// inheritance | |
// class Truck(color: String, model: String): FunnyCar(color, model) | |
class Truck(color: String, model: String): FunnyCar(color, model) { | |
override fun drive() { | |
println("a truck is being driven") | |
} | |
} | |
// class must be open in order to inherit it | |
open class FunnyCar( | |
val color: String = "Blue", | |
val model: String = "xmdle" | |
) { | |
init { | |
if (color == "Green") { | |
println("Yayy Green") | |
} else { | |
println("$color is not green") | |
} | |
} | |
fun speed(minSpeed: Int, maxSpeed: Int) { | |
println("min speed: $minSpeed\nmax speed: $maxSpeed") | |
} | |
open fun drive() { | |
println("car is being driven") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment