Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


2 Answers

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

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]")
like image 36
gcx11 Avatar answered Mar 03 '26 21:03

gcx11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!