1

I'm trying to follow the "Head First Kotlin" book exercises and I wrote the following code:

val numList = arrayOf(1,2,3);
var x = 0;

fun main() {
    while (x < 3) {
        println("Item $x is $numList[x]");
        x += 1;
    }
}

Kotlin printed:

Item 0 is [Ljava.lang.Integer;@30f39991[x]
Item 1 is [Ljava.lang.Integer;@30f39991[x]
Item 2 is [Ljava.lang.Integer;@30f39991[x]

But I expected to be:

Item 0 is 1
Item 1 is 2
Item 3 is 3

What am I doing wrong? Any help would be greatly appreciated!

  • And just FYI, the [semicolons `;` are not needed](https://stackoverflow.com/a/39319228/1431750) in Kotlin. They are inferred in most cases, with exceptions listed in the linked answer. – aneroid May 12 '21 at 23:30

1 Answers1

2

What you are missing are curly braces, try:

println("Item $x is ${numList[x]}");

Explanation: numList[x] is actually a method call. When using Kotlin's String interpolation you have to use {} when accessing the result of a method, function, or accessing a property. Without them, Kotlin inteprets your code as you'd like to print an array (which in Java and Kotlin does not override toString method, hence the 'strange output') and a string [x].

Examples:

val propertyAccess = "This is a ${user.name}"
val methodCall = "The result is ${anObject.getResult()}"
val functionCall = "5th Fibonacci number is ${fib(5)}"
ttarczynski
  • 949
  • 1
  • 10
  • 19