首页 > 解决方案 > kotlin中times方法的作用是什么?

问题描述

我是编程世界的新手,我正在研究运算符重载,我希望您向我解释一下 times 方法在本练习中实现的功能。

class Vector {
    val arreglo = IntArray(5)

    fun cargar() {
        for (i in arreglo.indices)
            arreglo[i] = (Math.random() * 11 + 1).toInt()
    }

    fun imprimir() {
        for (elemento in arreglo)
            print("$elemento ")
        println()
    }

    operator fun times(valor: Int): Vector {
        var suma = Vector()
        for (i in arreglo.indices)
            suma.arreglo[i] = arreglo[i] * valor
        return suma
    }
}

fun main(args: Array<String>) {
    val vec1 = Vector()
    vec1.cargar()
    vec1.imprimir()
    println("El producto de un vector con el número 10 es")
    val vecProductoEnt = vec1 * 10
    vecProductoEnt.imprimir()
}

标签: androidandroid-studiokotlinintellij-ideakotlin-coroutines

解决方案


函数时间重载运算符时间 (*) 并允许您编写表达式 vec1 * 10 将 Vector 的每个元素乘以 10。


推荐阅读