Last Updated on December 20, 2020 by AbdurRahman G Official | Md Ghufran Salafi
Classes and object instances in Kotlin:
Learn more
- Vocabulary for Android Basics in Kotlin
- Random number generation (Wikipedia)
- The Mind-Boggling Challenge of Designing 120-sided Dice
- Classes in Kotlin
- Function declarations in Kotlin
- Returning a value from a function
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 anIntRange
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 withDice(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 therandom()
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()
}
}