while-loopkotlinkotlin-extension

While loop in Kotlin Programming Language


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])
   }
}

Solution

  • 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).