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
ephemient
01/06/2021, 4:55 AM
your
operator fun plus
is not returning anything
a
alex cole
01/06/2021, 5:02 AM
Can it not be a void function that calls a different function that returns something?
c
Chrimaeon
01/06/2021, 9:08 AM
You have to return from the operator what the other function returns.
v
Vampire
01/06/2021, 12:18 PM
You probably confuse it with the expression syntax: