1

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])
   }
}
1
  • 1
    What is unclear? while expects a boolean expression. i-- is of type Int. Commented Jun 1, 2017 at 6:52

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

Kotlin while loops manual

while (x > 0) {
    x--
}

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

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.