Practice Time: Constructors and Init

 


// File:            Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/17/2023
// Email: nolvertou@gmail.com
// Description: Practice Time of constructors and init

fun main() {
// TODO 4: Instead of the list of spices as Strings you used earlier, create a list of Spice objects and give
// each object a name and a spiciness level.
val spiceObject = listOf( Spice("curry", "mild"),
Spice("pepper", "hot"),
Spice("cayenne", "medium"),
Spice("ginger", "mild"),
Spice("red curry", "hot"),
Spice("green curry", "medium"),
Spice("red pepper", "hot"))

println("Spicy Level: ${spiceObject[0].heat}")

// TODO 6: Print a list of spices that are spicy or less than spicy. Hint: Use a filter and the heat property.
println(spiceObject.filter { it.heat == 3})
println(spiceObject.filter { it.heat == 1 })
}



// TODO 1: Create a new class, Spice.
// TODO 2: Pass in a mandatory String argument for the name, and a String argument for the level of
// spiciness where the default value is mild for not spicy.
class Spice(var name: String, var spiciness: String = "mild") {

// TODO 3: Add a variable, heat, to your class, with a getter that returns a numeric value for each type of spiciness.
var heat: Int
get() {
return when(spiciness){
"mild" -> 1
"medium" -> 2
"hot" -> 3
"extra hot" -> 4
"extremely hot" -> 5
else -> 0
}
}
set(value) {heat = value}
// TODO 5: Add an init block that prints out the values for the object after it has been created. Create a spice.
init {
println("name: $name, spiciness = $spiciness")
}

// TODO 7: Because salt is a very common spice, create a helper function called makeSalt().
fun makeSalt(){
println("Adding Salt")
}

}
Output:
name: curry, spiciness = mild
name: pepper, spiciness = hot
name: cayenne, spiciness = medium
name: ginger, spiciness = mild
name: red curry, spiciness = hot
name: green curry, spiciness = medium
name: red pepper, spiciness = hot
Spicy Level: 1
[Spice@378fd1ac, Spice@49097b5d, Spice@6e2c634b]
[Spice@37a71e93, Spice@7e6cbb7a]




Comments

Popular posts from this blog