variablestypeskotlin

unable to print multiple Boolean in Kotlin


i'm beginning with kotlin language

fun main (args:Array<String>){


    var flag1:Boolean= true //Explicit declaration
    var flag2: =false //Implicit declaration

     println(flag2 + "and " + flag1)

     println(flag1)
     println(flag2)

}

in above code i have declared 2 type of boolean Explicit and Implicit declaration

for above code i would say expect following ouput :-

false and true 

true

false

but i'm getting following erroe :- error given by IDE

can anyone explain where did i go wrong ?


Solution

  • For that compiler error, change this:

    println(flag2 + "and " + flag1)
    

    to this:

    println("$flag2 and $flag1")
    

    Kotlin is strongly typed language and you can't use plus operator on String and Boolean types.

    But you can use string interpolation, with $ operator inside a string literal.

    You could also make it compile with overloaded plus operator on the Boolean type by adding this:

    operator fun Boolean.plus(s: String): String {
        return this.toString() + s
    }