what is the function of the method times in kotlin?

Viewed 803

I am new to the world of programming and I am working on operator overload, I would like you to explain to me what function the times method fulfills in this exercise.

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()
}
2 Answers

Function times overloads operator times (*) and lets you write expression vec1 * 10 to multiply every element of Vector by 10.

operator fun times(valor: Int): Vector 

this is the function invoked at this line val vecProductoEnt = vec1 * 10.

you can read more about it here

Related