Kotlin Basics Flashcards
.
How do you define a simple printHello() function in Kotlin?
fun printHello() {
println(“Hello”)
}
What are the basic mathematical operators in Kotlin?
+, -, *, /, %
What are the increment and decrement operators in Kotlin?
nb// remeber pre and post
: ++ (increment), – (decrement)
pre = ++a . shows me exact value of a but if I print later it will increase
post =a++
What is the syntax for calling numeric operator methods on numbers in Kotlin?
2.times(3) // Output: 6
3.5.plus(4) // Output: 7.5
2.4.div(2) // Output: 1.2
What are the integer data types in Kotlin?
Long (64 bits)
Int (32 bits)
Short (8 bits)
What is type casting in Kotlin? Provide an example of casting Int to Byte.
he process of converting an object from one data type to another,
val i: Int = 6
println(i.toByte()) // Output: 6
How do you use underscores for long numbers in Kotlin?
val oneMillion = 1_000_000
val idNumber = 999_99_9999L
How do you perform string concatenation in Kotlin using variable interpolation?
val numberOfDogs = 3
val numberOfCats = 2
“I have $numberOfDogs dogs and $numberOfCats cats”
What is a string template in Kotlin? Provide an example.
allows embedding variables or expressions inside a string using the $ symbol
val i = 10
println(“i = $i”) // Output: i = 10
Q: What are the mutable and immutable variables in Kotlin?
Mutable (can be changed): var, e.g., var count = 1
n
Immutable(cant change): val, e.g., val name = “Jennifer”
How does an if/else statement work in Kotlin? Provide an example.
val numberOfCups = 30
val numberOfPlates = 10
if (numberOfCups > numberOfPlates) {
println(“Too many cups!”)
} else {
println(“Not enough cups!”)
}
What is a when statement in Kotlin? Provide an example.
a conditional expression that acts like a switch-case, allowing multiple conditions to be checked in a concise and readable way.
when (results) {
0 -> println(“No results”)
in 1..39 -> println(“Got results!”)
else -> println(“That’s a lot of results!”)
}
How do you declare and iterate over an array in Kotlin?
val pets = arrayOf(“dog”, “cat”, “canary”)
for (element in pets) {
print(element + “ “)
}
// Output: dog cat canary
What is the purpose of the safe call operator (?) in Kotlin?
it indicates that a variable can be null. Example:
numberOfBooks = numberOfBooks?.dec() ?: 0
What is the Elvis operator (?:) used for in Kotlin?
It’s used to provide a default value when a nullable variable is null:
numberOfBooks = numberOfBooks?.dec() ?: 0