2

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 ?

Ashu_FalcoN
  • 916
  • 2
  • 10
  • 21

2 Answers2

7

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
}
Marko Devcic
  • 1,069
  • 2
  • 13
  • 16
3

In Java, it performs string conversion when you concatenate a string with any type of object. For example,

System.out.println(true + " and false");    //Output: true and false

In Kotlin, string conversion doesn't exist. Alternatively, you may use string templates for that.

println("$flag2 and $flag1")

Besides, since Kotlin's String class provide plus(Any?) function which receives any type as parameter, so the following line of code is still valid:

println("$flag2 and " + flag1)

Here is a discussion on this design.

BakaWaii
  • 6,732
  • 4
  • 29
  • 41