user9900987
user9900987

Reputation:

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

Upvotes: 3

Views: 116

Answers (3)

Alexey Soshin
Alexey Soshin

Reputation: 17721

Let's break it one by one:

println("$_array[3]") 

Same as println("${_array}[3]") - [3] is just a string here, not interpolated

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

Entire _array[3] is interpolated

println(_array[3]) 

Same as println(_array[3].toString())

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

Your array is Array<Any>. plus() is not defined for (Any,String)

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

plus() is defined for pair (String,Any), and it returns a string

Upvotes: 2

user8959091
user8959091

Reputation:

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

Upvotes: 4

gcx11
gcx11

Reputation: 128

When you use complex expression in string template, you have to wrap it inside curly braces. But that is optional for single variable.

So, this line

println("$_array[3]")

means same thing as

println(_array.toString() + "[3]")

Upvotes: 2

Related Questions