首页 > 解决方案 > 纽贝印刷类型

问题描述

我正在尝试遵循“Head First Kotlin”书籍练习,并编写了以下代码:

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

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

Kotlin 打印:

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

但我希望是:

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

我究竟做错了什么?任何帮助将不胜感激!

标签: kotlin

解决方案


您缺少的是花括号,请尝试:

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

解释:numList[x]实际上是一个方法调用。使用 Kotlin 的字符串插值时,您必须{}在访问方法、函数或访问属性的结果时使用。没有它们,Kotlin 会解释您的代码,因为您想打印一个数组(在 Java 和 Kotlin 中它不会覆盖toString方法,因此是“奇怪的输出”)和一个字符串 [x]。

例子:

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

推荐阅读