Skip to content

Instantly share code, notes, and snippets.

@anztrax
Created January 25, 2025 15:46
Show Gist options
  • Save anztrax/0ab7f0efee5e7e85b9e63dff60c947a4 to your computer and use it in GitHub Desktop.
Save anztrax/0ab7f0efee5e7e85b9e63dff60c947a4 to your computer and use it in GitHub Desktop.
scratch_1.kt
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class RangeRegulator(
initialValue: Int,
private val minValue: Int,
private val maxValue: Int,
) : ReadWriteProperty<Any?, Int> {
var fieldValue = initialValue;
override fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return fieldValue;
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
if (value in minValue..maxValue) {
fieldValue = value;
}
}
}
/**
* methods
*/
fun learnSelection() {
val trafficLightColor = "Yellow"
if (trafficLightColor == "Red") {
println("Stop")
} else if (trafficLightColor == "Yellow") {
println("Slow")
} else if (trafficLightColor == "Green") {
println("Go")
} else {
println("Invalid traffic-light color")
}
}
fun learnWhen() {
val trafficLightColor = "Yellow";
when (trafficLightColor) {
"Red" -> println("Stop")
"Yellow" -> println("Stop")
"Green" -> println("Go")
else -> println("Invalid traffic-light color")
}
var x = 3
when (x) {
2 -> println("x is a prime number between 1 and 10.")
3 -> println("x is a prime number between 1 and 10.")
5 -> println("x is a prime number between 1 and 10.")
7 -> println("x is a prime number between 1 and 10.")
else -> println("x isn't a prime number between 1 and 10")
}
x = 10
when (x) {
2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
else -> println("x isn't a prime number between 1 and 10")
}
val y: Any = "Yellow";
when (y) {
2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
is Int -> println("x is an integer number, but not between 1 and 10.")
else -> println("x isn't an integer number")
}
// using if , elseif, else of
val trafficLightColor2 = "Black";
val message = if (trafficLightColor2 == "Red") "Stop"
else if (trafficLightColor2 == "Yellow") "Slow"
else if (trafficLightColor2 == "Green") "Go"
else "Invalid traffic-light color"
println(message)
}
fun learnNullity() {
fun checkActorNameLength(name: String?) {
if (name != null) {
println("The number of characters in your favorite actor's name is ${name.length}.")
} else {
println("You didn't input a name.")
}
}
fun getActorNameLength(name: String?): Int {
return if (name != null) {
name.length
} else {
0
}
}
fun getActorNameLengthWithElvisOperator(name: String?): Int {
return name?.length ?: 0;
}
// nullable string
var favouriteActor: String? = null
checkActorNameLength(favouriteActor);
println("actor name length : ${getActorNameLength(favouriteActor)}")
favouriteActor = "Sandra Oh"
checkActorNameLength(favouriteActor);
println("actor name length : ${getActorNameLengthWithElvisOperator(favouriteActor)}")
}
fun learnClasses() {
open class SmartDevice protected constructor(
val name: String = "Android TV",
val category: String = "Entertainment"
) {
open val deviceType = "unknown"
var deviceStatus = "online"
private set
open var speakerVolume = 2
get() {
return field
}
set(value) {
if (value in 0..100) {
field = value
}
}
// secondary constructor
constructor(
name: String,
category: String,
statusCode: Int
) : this(name, category) {
deviceStatus = when (statusCode) {
0 -> "Offline"
1 -> "Online"
else -> "Unknown"
}
}
open fun turnOn() {
deviceStatus = "on"
}
open fun turnOff() {
deviceStatus = "off"
}
}
class SmartTVDevice(deviceName: String, deviceCategory: String) :
SmartDevice(name = deviceName, category = deviceCategory) {
override val deviceType = "Smart TV"
override var speakerVolume = 2
set(value) {
if (value in 0..100) {
field = value
}
}
private var channelNumber by RangeRegulator(initialValue = 1, minValue = 0, maxValue = 200)
fun increaseSpeakerVolume() {
speakerVolume++;
println("Speaker volume increased to ${speakerVolume}.")
}
fun nextChannel() {
channelNumber++;
println("Channel number increased to ${channelNumber}.")
}
override fun turnOn() {
super.turnOn()
println(
"$name is turned on. Speaker volume is set to $speakerVolume and channel number is " +
"set to $channelNumber."
)
}
override fun turnOff() {
super.turnOff()
println("$name turned off")
}
}
class SmartLightDevice(deviceName: String, deviceCategory: String) :
SmartDevice(name = deviceName, category = deviceCategory) {
override val deviceType = "Smart Light"
private var brightnessLevel by RangeRegulator(initialValue = 1, minValue = 0, maxValue = 100)
fun increaseBrightness() {
brightnessLevel++;
println("Brightness increased to ${brightnessLevel}.")
}
override fun turnOn() {
super.turnOn()
brightnessLevel = 2
println("$name turned on. The brightness level is $brightnessLevel.")
}
override fun turnOff() {
super.turnOff()
brightnessLevel = 0
println("Smart Light turned off")
}
}
class SmartHome(
val smartTVDevice: SmartTVDevice,
val smartLightDevice: SmartLightDevice
) {
var deviceTurnOnCount = 0
private set
fun turnOnTv() {
deviceTurnOnCount++
smartTVDevice.turnOn();
}
fun turnOffTv() {
deviceTurnOnCount--
smartTVDevice.turnOff();
}
fun increaseTvVolume() {
smartTVDevice.increaseSpeakerVolume();
}
fun changeTvChannelToNext() {
smartTVDevice.nextChannel()
}
fun turnOnLight() {
deviceTurnOnCount++
smartLightDevice.turnOn()
}
fun turnOffLight() {
deviceTurnOnCount--
smartLightDevice.turnOff()
}
fun increaseLightBrightness() {
smartLightDevice.increaseBrightness()
}
fun turnOnAllDevices() {
turnOnTv();
turnOnLight();
}
}
/**
* initiate objects
*/
// val samsung1 = SmartDevice()
// samsung1.turnOn()
val xiaomi1 = SmartDevice(
name = "Xiaomi TV",
category = "Smart TV",
statusCode = 1
)
println("${xiaomi1.name}, ${xiaomi1.deviceStatus}")
val xiaomi2 = SmartTVDevice(
deviceName = "xiaomi TV",
deviceCategory = "SmartPhone"
);
xiaomi2.nextChannel();
xiaomi2.increaseSpeakerVolume();
val smartLight1 = SmartLightDevice(
deviceCategory = "SmartLight",
deviceName = "Xioami Light",
)
val home1 = SmartHome(
smartTVDevice = xiaomi2,
smartLightDevice = smartLight1
)
home1.turnOffTv();
home1.turnOnTv();
home1.increaseTvVolume();
home1.changeTvChannelToNext();
home1.turnOnLight();
home1.increaseLightBrightness();
home1.turnOffLight();
home1.turnOnAllDevices();
println("deviceTurnOnCount : ${home1.deviceTurnOnCount}")
}
fun learnTypeAndLambdaExpression() {
fun trick() {
println("No treats!");
}
val treat: () -> Unit = {
println("Have a treat!")
}
fun trickOrTreat(isTrick: Boolean, extraTreat: ((Int) -> String)?): () -> Unit {
if (isTrick) {
return ::trick
}
if (extraTreat != null) {
println(extraTreat(5))
}
return treat
}
val trickFunction = ::trick
trick();
trickFunction();
treat();
val coins: (Int) -> String = { quantity -> "$quantity quarters" }
val pecels: (Int) -> String = { "$it pecels" }
val cupcake: (Int) -> String = { "Have a cupcake" }
val treatFunction = trickOrTreat(
isTrick = false,
extraTreat = pecels
)
treatFunction()
trickOrTreat(
isTrick = true,
null
)()
// high order function
repeat(5) {
trickOrTreat(false) {
"$it singkong"
}()
}
}
fun main() {
println(1 == 2)
learnSelection()
learnWhen()
learnNullity()
learnClasses()
learnTypeAndLambdaExpression()
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment