Classes and object instances in Kotlin

Last Updated on December 20, 2020 by AbdurRahman G Official | Md Ghufran Salafi

Classes and object instances in Kotlin:

 

Learn more

 

Solution code

fun main() {
    val myFirstDice = Dice(6)
    val diceRoll = myFirstDice.roll()
    println("Your ${myFirstDice.numSides} sided dice rolled ${diceRoll}!")
    
    val mySecondDice = Dice(20)
    println("Your ${mySecondDice.numSides} sided dice rolled ${mySecondDice.roll()}!")
}

class Dice (val numSides: Int) {

    fun roll(): Int {
        return (1..numSides).random()
    }
}

Summary

  • Call the random() function on an IntRange to generate a random number: (1..6).random()
  • Classes are like a blueprint of an object. They can have properties and behaviors, implemented as variables and functions.
  • An instance of a class represents an object, often a physical object, such as a dice. You can call the actions on the object and change its attributes.
  • You can supply values to a class when you create an instance. For example: class Dice(val numSides: Int) and then create an instance with Dice(6).
  • Functions can return something. Specify the data type to be returned in the function definition, and use a return statement in the function body to return something. For example: fun example(): Int { return 5 }

 

Practice on your own

Do the following:

  • Give your Dice class another attribute of color and create multiple instances of dice with different numbers of sides and colors!
  • Create a Coin class, give it the ability to flip, create an instance of the class and flip some coins! How would you use the random() function with a range to accomplish the coin flip?

 

Solution code of AbdurRahman G:

fun main() {
// //Assigning Values
val myFirstDice = Dice(6)
//Print Dice
println(“Your ${myFirstDice.numSides} sided dice rolled ${myFirstDice.roll()}!”)

val mySecondDice = Dice(20)
println(“Your ${mySecondDice.numSides} sided dice rolled ${mySecondDice.roll()}!”)
}

class Dice (val numSides: Int) {

fun roll(): Int {
return (1..numSides).random()
}

}

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *