I'd like to build the equivalent of:
def applyWithHList2[A1, A2, R, L <: HList](l: L, f: Function2[A1, A2, R]): Try[R]
The values in the list are such that in the N choose 2 possible value combinations of l.unify
there is at most one that could be used to call the function. No additional type information is available.
If there is no way to call the function, the result should be Failure
with MatchError
. Otherwise, the result should be Try(f(a1, a2))
.
I am still getting used to shapeless and would appreciate suggestions for how to approach this problem.
Funnily enough it's a lot easier to write a version that just doesn't compile if appropriately typed elements aren't available in the
HList
:If you really want a runtime error (in a
Try
) for cases where there's not an applicable pair, you could use the defaultnull
instance trick:If you find that unpleasant (and it is), you could use a custom type class:
And then:
But that's a lot of work just to throw away some compile-time safety.
Note that none of these approaches enforce the constraint that there's only at most pair of elements in the
HList
that the function can be applied to, since I read that as a pre-condition in your question. It'd definitely be possible to write a solution that enforced the constraint at compile time (and it might even be a bit shorter than theMaybeSelect2
implementation above).