Search code examples
kotlinstring-interpolation

println() produces different output


fun main(args: Array<String>) {

  var _array = arrayOf(1 , 2 , 3.14 , 'A', "item" , "a b c d", 4)

  println("$_array[3]")  // [Ljava.lang.Object;@1b6d3586[3]
  println("${_array[3]}") // A
  println(_array[3]) // A

  println( _array[3] + " is _array's item") // ERROR
  println( "" + _array[3] + " is _array's item") // A is _array's item

} 

I am confused why the code above makes different output


Solution

  • println("$_array[3]")  // [Ljava.lang.Object;@1b6d3586[3]
    

    prints the _array object reference followed by [3], you use string interpolation only for the _array argument

    println("${_array[3]}") // A
    

    prints the 4th element of _array, you use string interpolation for the _array[3] argument

    println(_array[3]) // A
    

    prints the 4th element of _array (same as above)

    println( _array[3].toString() + " is _array's item") // ERROR
    

    it needs toString() to get printed because the elements of _array are of type Any and the + sign after it is inconclusive
    it prints the 4th element of _array

    println( "" + _array[3] + " is _array's item") // A is _array's item
    

    it does not need toString() as it is preceded by an empty string and the + sign is interpreted by the compiler as string concatenation so it prints the 4th element of _array