Boolean functions in Kotlin

Kotlin Boolean functions :

Boolean is used to represent a value that is either true or false. Booleans are useful for decision-making statements. Kotlin provides many methods for logical operations, finding the string representation, equality check, hashcode, etc. In this tutorial, we will check these functions with examples :

and, or and not :

and performs logical and operation between two boolean values. It returns the final boolean value.

Similarly, or performs logical or operation between two boolean values and not returns the inverse of the boolean.

fun main(args: Array<string>) {
    var t = true;
    var f = false;

    println("t.and(t): "+t.and(t));
    println("t.and(f): "+t.and(f));
    println("f.and(t): "+f.and(t));
    println("f.and(f): "+f.and(f));
    println("t.or(t): "+t.or(t));
    println("t.or(f): "+t.or(f));
    println("f.or(t): "+f.or(t));
    println("f.or(f): "+f.or(f));
    println("not(t): "+t.not());
    println("not(f): "+f.not());
}

Output :

t.and(t): true
t.and(f): false
f.and(t): false
f.and(f): false
t.or(t): true
t.or(f): true
f.or(t): true
f.or(f): false
not(t): false
not(f): true

Kotlin boolean and or not

xor :

It performs the logical xor operation and returns the result boolean value.

fun main(args: Array<string>) {
    var t = true;
    var f = false;

    println("t.xor(t): "+t.xor(t));
    println("t.xor(f): "+t.xor(f));
    println("f.xor(t): "+f.xor(t));
    println("f.xor(f): "+f.xor(f));
}

Output :

t.xor(t): false
t.xor(f): true
f.xor(t): true
f.xor(f): false

compareTo :

compareTo is used to compare one boolean with another. It returns zero if both are equal, negative number if it is less than the other value and a positive number if it is greater than the other value.

fun main(args: Array<string>) {
    var t = true;
    var f = false;

    println("t.compareTo(t): "+t.compareTo(t));
    println("t.compareTo(f): "+t.compareTo(f));
    println("f.compareTo(t): "+f.compareTo(t));
    println("f.compareTo(f): "+f.compareTo(f));
}

Output :

t.compareTo(t): 0
t.compareTo(f): 1
f.compareTo(t): -1
f.compareTo(f): 0

equals :

It returns one boolean value indicating one boolean is equal to another boolean or not.

fun main(args: Array<string>) {
    var t = true;
    var f = false;

    println("t.equals(t): "+t.equals(t));
    println("t.equals(f): "+t.equals(f));
    println("f.equals(t): "+f.equals(t));
    println("f.equals(f): "+f.equals(f));
}

It will print :

t.equals(t): true
t.equals(f): false
f.equals(t): false
f.equals(f): true

hashCode :

It returns the hashcode integer value for a boolean :

toString :

Returns the string representation of the boolean value: true or false.