我初始化了INT的二维数组,如下所示

var array = Array(n) { Array(n) { 0 } }

然后我在array上做了一些逻辑运算来填充值.

when it comes to converting Row values of array (so Array<Int> type) to IntArray type using .toIntArray(), it behaves differently depending on how to execute corresponding function calls.(toIntArray() and contentToString())
Please look at this screenshot that I ran on XXX.kts scratch file on Android Studio. enter image description here

如果为test2,则值返回到0.test使用我前面提到的执行的逻辑来保持填充值.

我搞不懂这里到底是怎么回事.

我会感激的

  1. 如果您能解释为什么调用相同的函数,但调用它们的方式不同会导致不同的输出.
  2. 如果您能建议一种将Array<Int>转换为IntArray的方法(我猜可能是二维数组)

[UPDATE]
Sorry that I didn't attach logic part of code.
The code is like this.(I changed a logic part but it is almost identical. Logic is basically assigning integers in the array.)

for (i in 0..5) {
    for (j in 0..5) {
        array[i][j] = i + j
    }
}

val test = array[0]
println(test.contentToString())
val test2 = test.toIntArray()
println(test.toIntArray().contentToString())
println(test2.contentToString())

and the screenshot with the code look like this below.enter image description here

[UPDATE 2]
just to be clear for running the code, make sure to initialize n to be specific number at the very beginning before initializing array. so it should be something like this.

val n = 6
var array = Array(n) { Array(n) { 0 } }

推荐答案

我可以在Scratch中重现它,但它在我作为Kotlin应用程序运行的Main中运行得很好.我认为IntelliJ使用的交互模式肯定有漏洞.(勾选"使用REPL"时工作正常)

这就产生了不良行为:

var n = 0

val array = Array(6) { Array(6) { 0 } }
for (i in 0..5) {
    for (j in 0..5) {
        array[i][j] = i + j
    }
}

val test = array[0]
println(test.contentToString())
val test2 = test.toIntArray()
println(test.toIntArray().contentToString())
println(test2.contentToString())

我已经为IntelliJ提交了a bug report份申请.

这似乎与this bug有关,后者演示了一个更简单的情况(我刚刚测试了它,显示了不正确的值10):

// code from related bug report
var a = 10
a = 20
val t = a
t // prints 10, but 20 is expected

相关漏洞是四年前提交的,最后一次 comments 是在2022年.我投了赞成票,希望新的错误能让人再次关注这个问题.

Kotlin相关问答推荐

最好的方法来创建一个 map 在kotlin从两个列表

调用即发即忘方法--哪个作用域?

将文本与文本字段的内容对齐

Kotlin中一个接口的实现问题

Spring Boot 3:为Kotlin中的TestRestTemplate配置读取超时

如何注入返回通用列表的转换器?

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

如何在 Kotlin 中不受约束?

Kotlin 中私有集的完整语法 struct 是什么?

使用纯 Kotlin 函数作为 Junit5 方法源

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

在 Spring Framework 5.1 中注册具有相同名称的测试 bean

如何在 Kotlin 中传递有界通配符类型参数?

Kotlin惰性默认属性

什么是开放式property?为什么我不能将其设置器设为private私有?

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

将 Double 转换为 ByteArray 或 Array Kotlin

@StringRes、@DrawableRes、@LayoutRes等android注释使用kotlin参数进行判断

有没有办法在Kotlin中设置一个私有常量

Android Jetpack Compose - 图像无法zoom 到框的宽度和高度