In my kotlin code i am getting Type mismatch(inferred type is Int but Boolean was expected) error.
fun main(args: Array<String>) {
var i = args.size
while (i--){
println(args[i])
}
}
In my kotlin code i am getting Type mismatch(inferred type is Int but Boolean was expected) error.
fun main(args: Array<String>) {
var i = args.size
while (i--){
println(args[i])
}
}
while (x > 0) { x-- } do { val y = retrieveData() } while (y != null) // y is visible here!
First of all, args.size is +1 greater than the last element's index in the array. Therefore, you must subtract 1 from the resulting value: args.size-1 (or you can use i-1). Additionally, just like using an if-statement in Kotlin, a while-loop requires a Boolean expression, i.e. while(true/false) {...}.
fun methodWith(args: Array<String>) {
var i = args.size - 1 // args.size = 2
while (i >= 0) {
println(args[i])
i -= 1
}
}
fun main() {
val strings = arrayOf("Kotlin","Java","Python")
methodWith(strings)
}
You can also declare a Boolean property for a while's condition.
fun methodWith(args: Array<String>) {
var i = args.size // args.size = 3
var bool: Boolean = true
while (bool) {
println(args[i-1]) // -1
i -= 1
if (i <= 0) bool = false
}
}
fun main() {
val strings = arrayOf("Kotlin","Java","Python")
methodWith(strings)
}
Result:
Python
Java
Kotlin