Kotlin Boolean & Usage Examples | Android Introduction #10
In this reading, you’ll learn more about what Boolean values are and how to perform basic operations resulting in a Boolean.
Boolean
Numbers and Strings have already been introduced in this course, and now the last basic operation type to learn about is a Boolean. A Boolean has two possible values, true and false, and can be used to tell users whether something is true or not. For instance, if you implement a website, you need to ask the user to accept the cookie policy. You then need to store information on whether the user accepted it or not, which can be represented by a variable. It is either true because the user accepted the policy or false because the user rejected the policy.
var cookiePolicyAccepted: Boolean = true
When you compare two values, the result is of type Boolean. You can check if two values are equal by using the double equal sign, and the result will always be a Boolean, so either true or false. In Kotlin, you can use either the == operator or the equals() when comparing strings.
println(20 == 10) // false
You can also check if two values are not equal to each other. For that, use an exclamation mark and an equal sign. You will notice that the results are exactly the opposite of what you had when you used the double equal sign.
println("A" == "A") // true
println("A" == "B") // false
println(10 == 10) // true
println(20 == 10) // false
println("A" != "A") // false
println("A" != "B") // true
println(10 != 10) // false
println(20 != 10) // true
You can also compare values with less-than or greater-than signs. Here are a few examples of comparing numbers.
println(10 > 10) // false
println(20 > 10) // true
println(10 > 20) // false
println(10 < 10) // false
println(20 < 10) // false
println(10 < 20) // true
As you can note, two identical values are not less-than or greater-than. If you want to check if a value is less-than or equal-to or greater-than or equal-to, there are special operators for that. You use the less-than or greater-than sign followed by the equal sign.
println(10 >= 10) // true
println(20 >= 10) // true
println(10 >= 20) // false
println(10 <= 10) // true
println(20 <= 10) // false
println(10 <= 20) // true
You may have noticed that all of those comparisons produce either true or false results, which you call a Boolean type. You will find this useful in a subsequent lesson, for instance, when using the if-condition to execute some code only if a comparison returns true. Keep reading to learn how to create these logical expressions.