Day34 of #100DaysOfCode
2 min readMar 12, 2022
Hii folks 🙌
Today I learned more concepts in Kotlin — including classes, objects, and conditionals as well as to create an interactive app following Unit 1 of Android Basics in Kotlin.
Unit 1: Kotlin basics
Pathway 4: Add a button to an app
Source: https://developer.android.com/courses/android-basics-kotlin/course
Classes and object instances in Kotlin
- Call the
random()
function on anIntRange
to generate a random number:(1..6).random()
fun main() {
val diceRange = 1..6
val randomNumber = diceRange.random()
println("Random number: ${randomNumber}")
}
- Classes are like a blueprint of an object. They can have properties and behaviors, implemented as variables and functions.
class Dice {
var sides = 6
fun roll() {
val randomNumber = (1..6).random()
println(randomNumber)
}
}
- An instance of a class represents an object, often a physical object, such as a dice. We can call the actions on the object and change its attributes.
fun main() {
val myFirstDice = Dice()
println(myFirstDice.sides)
myFirstDice.roll()
}
- We 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)
.
class Dice (val numSides: Int) { fun roll(): Int {
return (1..numSides).random()
}
}
- 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 }
fun roll(): Int {
val randomNumber = (1..6).random()
return randomNumber
}
That is all for Day34 ✅
Thanks for reading, See you tomorrow!