0

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])
   }
}
LF00
  • 27,015
  • 29
  • 156
  • 295
Rohit Parmar
  • 367
  • 1
  • 4
  • 19

3 Answers3

3

You have to provide a Boolean value as the argument of while. There's no auto-casting of Int to Boolean in Kotlin.

So you can't do while(i--), but you can, for example, do while(i-- != 0) or while(i-- > 0).

zsmb13
  • 85,752
  • 11
  • 221
  • 226
2

Kotlin while loops manual

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!
LF00
  • 27,015
  • 29
  • 156
  • 295
1

while expects a boolean (true/false), you give an integer (i-1). correct code could be:

fun main(args: Array<String>) {
   var i = args.size 
   while (i>=0){
    println(args[i])
    i--
   }
}
Fabian
  • 531
  • 4
  • 11