我正在使用这个代码.

fun main(args : Array<String>){

    val someArray : Array<Int> =  arrayOf(3,53,2,521,51,23,512,34,124);

    println("Original array is ")

    someArray.forEach {print("$it , ")}

    someArray.map({num -> num*2})

    println("Changed array is ")

    println()

    someArray.forEach { print("$it , ") }
}

But the map function does not seem to work. Here is what it prints

原始数组是

3 , 53 , 2 , 521 , 51 , 23 , 512 , 34 , 124 ,

My question is why is the array not doubling the value of its elements? What i am i missing here?

推荐答案

You could always define your own extension that does what you need:

fun <T> Array<T>.mapInPlace(transform: (T) -> T) {
    for (i in this.indices) {
        this[i] = transform(this[i])
    }
}

用法如下所示:

someArray.mapInPlace { num -> num * 2 }

Note that there are special non-generic classes for primitive arrays, such as IntArray (see also this question), so you should probably be using those instead of the generic one. Of course then you'd have to define this extension for each of them separately, like:

fun IntArray.mapInPlace(transform: (Int) -> Int) { ... }
fun DoubleArray.mapInPlace(transform: (Double) -> Double) { ... }

Kotlin相关问答推荐

在Kotlin中,有没有一种函数方法将一个列表(N个元素)映射到一个相邻元素之和列表(N—1个元素)?

Kotlin是否针对范围和进度优化sum()?

Spring Boot Bean验证器未触发

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

Scala性状线性化等价于Kotlin

Kotlin扩展函数未调用Hibernate/JPA中的重写函数

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

如何使用成员引用在 Kotlin 中创建属性的分层路径

为什么 Kotlin 的 null 安全性不能与局部变量初始化器一起正常工作?

如何通过 compose 处理剪切区域?

Picasso 回调

在 Scaffold Jetpack Compose 内的特定屏幕上隐藏顶部和底部导航器

如何在 Kotlin 中为变量设置监听器

任何处理器都无法识别以下选项:'[kapt.kotlin.generated, room.incremental]'

Java中lazy的Kotlin类似功能是什么?

如果kotlin已经有了getter和setter,为什么在数据类中有componentN函数?

Kotlin 中内部可见性修饰符的范围

Recyclerview: listen to padding click events

是否可以在不使用class的情况下将 Mockito 与 Kotlin 一起使用?

任务':app:kaptDebugKotlin'的Kotlin执行失败