[swift-evolution] Polymorphic behavior for overloaded == (and other) operators

Frederick Kellison-Linn fred.kl at me.com
Wed Dec 9 00:32:06 CST 2015


Currently, implementing an ā€˜==ā€˜ function for a custom class can be somewhat cumbersome. In the simple hierarchy:

class A {
    var a: Int
    init(_ a: Int) {
        self.a = a
    }
}

class B : A {
    var b: Int
    init(_ b: Int, _ a: Int) {
        self.b = b
        super.init(a)
    }
}

A reasonable implementation of == would seem to be

func ==(lhs: A, rhs: A) -> Bool {
    return lhs.a == rhs.a
}

func ==(lhs: B, rhs: B) -> Bool {
    return lhs.a == rhs.a &&
           lhs.b == rhs.b
}

However, this fails in the case that the static type of compared variables differs from their dynamic type. E.g:

let x = A(3)
let y: A = B(3, 4)

x == y // true

The immediately obvious solution is to add a check to every == implementation that may need to be implemented for a subtype:

func ==(lhs: A, rhs: A) -> Bool {
    if (lhs.dynamicType != rhs.dynamicType) {
        return false
    }
    return lhs.a == rhs.a
}

But this results in annoying boilerplate for what should be a simple computation, and furthermore fails to solve every case:

let w: A = B(1, 2)
var z: A = B(1, 3)

w == z // still true

Iā€™d be interested to know if there is any interest taken in this problem and whether possible solutions have been discussed. If == were instead behaved as if it were a method of its first argument (as in a .equals(other) method) then the solution above is sufficient to avoid returning the wrong result, but being forced to use .dynamicType for something as basic as equality checking seems cumbersome to me.

FKL
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151209/abcbecb3/attachment.html>


More information about the swift-evolution mailing list