Type-checked triple equals: Scala test

We all write scala tests (at least our resume says so) and we all also use the === operator for assertion. However sometimes mistakes can be made in the code or within the tests that are only caught when the tests start failing ( a runtime check).

using the === in command line

The above tests reveal the nature of ===. Values are checked for equality and their types are totally ignored at compile time. Also types like Int, Long which do not have any relationship can match each other. Sometimes this is not what the user wants.

What we would like is to have a equals check that also confirms the type of the two sides being compared. Here is when the TypeCheckedTripleEquals comes handy.

TypeCheckedTripleEquals provides === and !== operators that return Boolean, delegate the equality determination to an Equality type class, and require the types of the two values compared to be in a subtype/supertype relationship.

TypeCheckedTripeEquals flags the in equality of types at run time. The writer is hence forced to ensure the type compatibility of his values at compile time. This is useful when you are writing unit tests for a library that especially deals with compiler logic or provides a collection of new types.

So basically whenever you feel that the types of values should be also be considered in comparison then you should use the TypeCheckedTripleEquals.

If you feel the need to compare two types that are not compatible by default then there needs to be a conversion provided by you. We can use a widening type ascription. A type ascription is simply a colon and a type placed next to a variable, usually surrounded by parentheses. Since Seq[Int] is a common supertype of both Vector[Int] and List[Int], the type constraint can be satisfied by widening either to their common supertype, Seq[Int]:

Happy unit testing!!

Get the Medium app
