Questions on operator overloading. I am trying to ...
# getting-started
a
Questions on operator overloading. I am trying to overload the “+” operator to add to objects together but am given an error. However with my own add routine the function works. Could some one explain why? Questions on operator overloading. I am trying to overload the “+” operator to add to objects together but am given an error. However with my own add routine the function works. Could some one explain why?
Copy code
class ArrayND  {
    var nDimensionalArray: ArrayList<Double> = arrayListOf()
    private var shape = arrayOf<Int>()

    constructor (ndArray: Array<Double>, shape: Array<Int>){
        nDimensionalArray = arrayListOf(*ndArray)
        this.shape = shape
    }

    private fun whatIsTheShape(): Array<Int> {
        return shape
    }

    fun add(b: ArrayND): ArrayND {
        if (shape.contentEquals(b.whatIsTheShape())){
            val x = arrayListOf<Double>()
            for(i in  0 until nDimensionalArray.size){
                x.add(nDimensionalArray[i] + b.nDimensionalArray[i])
            }
            return ArrayND(x.toTypedArray(), shape)
        }
        else {
            return ArrayND(arrayOf<Double>(), arrayOf<Int>())
        }
    }

    operator fun plus(other: ArrayND){
        add(other)
    }

    fun print(){
        TODO("Work in more than one dimension")
        print("[")
        for(i in nDimensionalArray) {
            print("$i ")
        }
        print("]")
    }
}
e
your
operator fun plus
is not returning anything
a
Can it not be a void function that calls a different function that returns something?
c
You have to return from the operator what the other function returns.
v
You probably confuse it with the expression syntax:
operator fun plus(other: ArrayND) = add(other)
a
Thank you, it works now.