Generic Classes

Classes in Kotlin can have type parameters to create generic classes, just like in Java

// File:            Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/24/2023
// Email: nolvertou@gmail.com
// Description: Using generic classes

fun main() {
val stringList: MyList<String>

// Using generic Class
val intList: MyList<Int> = MyList()
intList.addItem(1)
println(intList.get(1))
}

class MyIntList{
fun get(pos: Int) : Int{ return 0 }
fun addItem(item: Int){}
}

class MyShortList{
fun get(pos: Int): Short{ return 0 }
fun add(item: Short){}
}

// Generic Class
class MyList<T>{
fun get(pos: T): T{
// TODO("implement")
return pos
}
fun addItem(item: T){}
}





Example 2: 
Main.kt
import generics.Aquarium

// File: Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/24/2023
// Email: nolvertou@gmail.com
// Description: Using a generic class

fun main() {
genericExample()
genericExample2()
}

fun genericExample(){

// Example 1: Using generic class
val aquarium = Aquarium<TapWater>(TapWater())
println("The waterSupply needs to be processed: "+aquarium.waterSupply.needsProcessed)

println("Lets process the water!")
println("We are adding chemical cleaners to the water, so it is being processed...")
aquarium.waterSupply.addChemicalCleaners()
aquarium.addWater()
println("The waterSupply needs to be processed: "+aquarium.waterSupply.needsProcessed)
aquarium.waterSupply.addChemicalCleaners()

}

fun genericExample2(){
// This does not look right, im able to pass a string in as a waterSupply
// This because type T does not have any bounds, so it can be set to any type,
// so, that could be a problem
// val aquarium2: Aquarium<String> = Aquarium("String")
// println(aquarium2.waterSupply)

// Another unexpected example is passing in nulls
// val aquarium3: Aquarium<Nothing?> = Aquarium(null)
// println(aquarium3.waterSupply)


}
WaterSupply Class
open class WaterSupply(var needsProcessed: Boolean)
LakeWater Class
class LakeWater: WaterSupply(true) {
fun filter(){
needsProcessed = false
}
}
TapWater Class
class TapWater: WaterSupply(true) {
fun addChemicalCleaners(){
needsProcessed = false
}
}

Generic Aquarium Class
package generics

import WaterSupply

// To ensure that our parameter must be nonnull, but it can still be any type
// class Aquarium<T>(val waterSupply: T) // This lets passing any type and nulls too
// class Aquarium<T: Any?>(val waterSupply: T) // This lets passing any type and nulls too
// class Aquarium<T: Any>(val waterSupply: T) // This lets passing any type (no nulls)
// class Aquarium<T: WaterSupply >(val waterSupply: T) // This lets passing only WaterSupply types
class Aquarium<T: WaterSupply>(val waterSupply: T){
fun addWater(){
// This acts as an assertion, and it will throw an illegal exception if its argument is false
check(!waterSupply.needsProcessed){"Water Supply needs processed!"}
println("adding water from $waterSupply")
}
}

Comments

Popular posts from this blog