Hi,
I am playing around with defining operators in Scala. I have the following code:
object Hello {
abstract class Element {
def &(e: Zero)
def &(e: One)
}
class Zero extends Element {
override def &(e: Zero): Zero = this
override def &(e: One): Zero = this
override def toString: String = "0"
}
class One extends Element {
override def &(e: Zero): Zero = e
override def &(e: One): One = this
override def toString: String = "1"
}
class Array2d {
val plane = Array.fill[Element](4, 4){ new Zero }
def setOne(x: Int, y: Int) = plane(y)(x) = new One()
def dump(): Unit = { plane.foreach(line => {line.foreach(print); println();}); println(); }
def &(other: Array2d) = {
for (y <- 0 to plane.length - 1) {
for (x <- 0 to plane(0).length - 1) {
val a: Element = plane(y)(x)
val b: Element = other.plane(y)(x)
plane(y)(x) = a & b
}
}
}
}
def main(args: Array[String]): Unit = {
val zero = new Zero()
val one = new One()
println(zero & zero) // 0
println(zero & one) // 0
println(one & zero) // 0
println(one & one) // 1
val arr1 = new Array2d()
val arr2 = new Array2d()
arr1.setOne(0, 0)
arr1.setOne(1, 1)
arr1.dump()
arr2.setOne(2, 2)
arr2.setOne(3, 3)
arr2.dump()
arr1 & arr2
arr1.dump()
}
}
My &
operator works fine for One
and Zero
. But I am not able to implement the & operator for 2d arrays filled with ones and zeros. How can I solve that? My IDE is complaining that plane(y)(x) = a & b
is interpreted as a recursive method without result type. However, the &
between a
and b
is supposed to be the Operator defined in the elements.