Is there a way to check if one of two givens is present?

Example:

def compare[A, B](x: A, y: B)(using A <:< B) = x == y
def compare[A, B](x: A, y: B)(using B <:< A) = x == y // error: Conflicting definitions

I would like to do something like:

def compare[A, B](x: A, y: B)(using A <:< B or B <:< A) = x == y

Is there a way to do this ?
(Apart from adding a DummyImplicit parameter)

I believe what you want is exactly this example: Compile-time operations

3 Likes

It did work !

inline def compare[A, B](x: A, y: B) = summonFrom:
  case _: (A <:< B) => x == y
  case _: (B <:< A) => x == y

But it has to be an inline method (for my purposes, that is fine)

Worst case you use the inline to dispatch to the appropriate handling method anyway. The code inlined at each callsite would then look like just calling the right one with no overhead.

1 Like

You can also use “old school” implicit resolution tricks like here: implicitlogic/src/main/scala/implicitlogic/Or.scala at master · Jasper-M/implicitlogic · GitHub

1 Like

There is an even easier solution: use |:

def compare[A, B](x: A, y: B)(using A <:< B | B <:< A) = x == y

I’m not sure it’s strictly equivalent, but for most use case it should be better

2 Likes