Beyond Liskov: Type Safe Equality in Scala

The idea that this is part of a broader problem gave me a thought. What if we describe the problem of e.g. “the answer to a == b is trivially known” as "the static type of a == b is the literal type false but your code clearly indicates that it’s handling all Boolean values (for instance it’s used in an if condition). This seems like a formal way to generalize this problem.

The first problem is that currently == doesn’t result in anything narrower than Boolean.

Second, it raises the question of what “clearly indicates” means. Certainly it implies that there shouldn’t be anything wrong with this code:

def doSomethingWithABoolean(parameter: Boolean): Unit = ???
doSomethingWithABoolean(1 == 2)

This code has a different, more general problem: it could be trivially simplified. That sounds like a reasonably thing to lint for. But what about these?

def thirdOfCircle = Math.Pi * 2 / 3
def timeToWaitInMillis = 5 * 60 * 1000

Those could be simplified but I don’t think they should (although an abstraction would be a good idea)

If we could somehow solve these issues then we might improve the quality of a lot of code.

2 Likes