Complete the code to assign the maximum of two numbers to max using an expression.
val max = if (a > b) [1] else b
if as a statement without returning a value.a.The if expression returns a if a is greater than b, otherwise b. This assigns the maximum value to max.
Complete the code to assign the result of the expression that returns the length of the string or 0 if the string is null.
val length = str?.length ?: [1]null as default which causes type mismatch.str.length which can cause a null pointer exception.The Elvis operator ?: returns 0 if str?.length is null, ensuring length is always an integer.
Fix the error in the expression that tries to assign the result of a when expression to a variable.
val result = when (x) {
1 -> "One"
2 -> "Two"
else -> [1]
}print("Other") which returns Unit, not String.null which may cause type mismatch.The when expression must return a value for all cases. Using "Other" returns a string, matching the other branches.
Fill both blanks to create a map of words to their lengths, including only words longer than 3 characters.
val lengths = words.filter { word -> word.length > 3 }.map { word -> [1] to [2] }.toMap()word.uppercase() as key which changes the word.word.count() which is not a Kotlin String method.The map keys are the words themselves (word) and the values are their lengths (word.length), filtered by length > 3.
Fill all three blanks to create a map of uppercase words to their lengths, including only words longer than 4 characters.
val result = words.filter { word -> word.length [3] 4 }.map { word -> [1] to [2] }.toMap()word instead of uppercase for keys.< instead of > for filtering.The map keys are uppercase words (word.uppercase()), values are their lengths (word.length), filtered by words longer than 4 characters (> 4).