Rohit Parmar
Rohit Parmar

Reputation: 397

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

Upvotes: 1

Views: 1880

Answers (4)

Andy Jazz
Andy Jazz

Reputation: 58053

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

Upvotes: 1

LF-DevJourney
LF-DevJourney

Reputation: 28529

Kotlin while loops manual

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!

Upvotes: 2

Fabian
Fabian

Reputation: 529

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

Upvotes: 0

zsmb13
zsmb13

Reputation: 89538

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

Upvotes: 4

Related Questions