【问题标题】:what is the function of the method times in kotlin?kotlin中times方法的作用是什么?
【发布时间】:2020-05-29 12:13:08
【问题描述】:

我是编程世界的新手,我正在研究运算符重载,我希望您向我解释一下 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()
}

【问题讨论】:

    标签: android android-studio kotlin intellij-idea kotlin-coroutines


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      operator fun times(valor: Int): Vector 
      

      这是在val vecProductoEnt = vec1 * 10这一行调用的函数。

      你可以阅读更多关于它here

      【讨论】:

        猜你喜欢
        • 2019-07-20
        • 2015-07-24
        • 2016-11-25
        • 2020-02-22
        • 2017-03-14
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多