Kris10an
Kris10an

Reputation: 569

Operator '==' cant be applied to 'Boolean' and 'Char'

So i want to compare three members of an array with as little code as possible. Heres what i did:

for(i in 0..2) {
    if(board[i][0] == board[i][1] == board[i][2]) {
        return true
    } else if(board[0][i] == board[1][i] == board[2][i]) {
        return true
    }
}

(All of the values ar Char's FYI) But it didnt work. I get this error message "Operator '==' cant be applied to 'Boolean' and 'Char'". I also tried using .equals, but that just didnt work. Any ideas on what to do?

Upvotes: 3

Views: 569

Answers (5)

Raymond Arteaga
Raymond Arteaga

Reputation: 4673

As the others said, your first comparison returns Boolean, and the second compares Boolean to Char.

You can use an extension function, and transitivity to simplify things:

fun Any.equalsAll(vararg others: Any):Boolean
{
    others.forEach {
        if(it!=this)
            return false
    }
    return true
}

and call:

 if (board[0][i].equalsAll(board[1][i], board[2][i]))

Upvotes: 0

user8959091
user8959091

Reputation:

Another approach:

for (i in 0..2) {
    if (board[i].toSet().size == 1)
        return true
    else if (board.map { it[i] }.toSet().size == 1)
        return true
}

Upvotes: 0

Pawel
Pawel

Reputation: 17248

You can write a small function to keep it more readable and tidy, especially if You need to do that comparison often:

fun allEqual(vararg items: Any) : Boolean {
    for(i in 1..(items.size-1)){
        if(items[0] != items[i]) return false
    }
    return true
}

And invoke simply by comma separating values:

allEqual(board[i][0], board[i][1], board[i][2])

Upvotes: 4

Avijit Karmakar
Avijit Karmakar

Reputation: 9388

You have included this condition:

if(board[i][0] == board[i][1] == board[i][2])

Firstly, this one is compared: board[i][1] == board[i][2]

After comparing, it returns true. After that if logic converts to:

if(board[i][0] == true)

Now, board[i][0] is a char and you are trying to compare it to a boolean which is not possible. That's why you are getting this error.

You have to change the logic to:

if((board[i][0] == board[i][1]) && (board[i][1] == board[i][2]))

So, your code will be:

for(i in 0..2) {
    if((board[i][0] == board[i][1]) && (board[i][1] == board[i][2])) {
        return true
    } else if((board[0][i] == board[1][i]) && (board[1][i] == board[2][i])) {
        return true
    }
}

Upvotes: 0

J. Van Heuit
J. Van Heuit

Reputation: 49

I don't know Kotlin specifically, but most* languages don't allow you to compare 3 values at the same time. What your error message is communicating is that your code ends up comparing

"Is board[i][0] equal to board[i][1]?" which is true/false (Boolean)

to

board[i][2], which is a Char.

*I don't know of any, but maybe there's one out there that does.

Upvotes: 3

Related Questions