+ 4

can someone please explain this code to me i'm clueless

fun alwaysReturnsNull(position: Int): String? { if ((position % 10) == 0) { when (position) { 10 -> "one" 20, 30 -> "two" else -> "three" } } return null } fun returnsNullableString(position: Int): String? { if ((position % 10) == 0) { return when (position) { 10 -> "one" 20, 30 -> "two" else -> "three" } } return null }

27th Dec 2019, 5:53 PM
voyes
voyes - avatar
2 Answers
0
The first always returns null. The if statement does not have any effect on the result. The if statement is entered for position of 0, 10, 20, 30, 40, ... The when statement produces values always that are ignored. "one" for 10, "two" for 20 & 30, and "three" for all others.
27th Dec 2019, 7:34 PM
John Wells
John Wells - avatar
0
The second is similar, but the if and when have an affect. Now, the result of the when are returned so 0 yields "three", 1 to 9 yield null, 10 yields "one", 11 to 19 yield null, 20 yields "two", 21 to 29 yield null, ...
27th Dec 2019, 7:38 PM
John Wells
John Wells - avatar