In below example, I want to define a contains
method that doesn't compile if a
and b
are not of the same base type.
- In
contains1
impl, ifa
isSeq[Int]
and b isString
,T
is derived to beAny
, and it compiles. This is not I want. - In
contains2
impl, ifa
isSeq[Int]
and b isString
, then it doesn't compile. The behavior is what I want.
def contains1[T](a: Seq[T], b: T): Boolean = a.contains(b)
println(contains1(Seq(1,2,3), "four")) // false
def contains2[T: Ordering](a: Seq[T], b: T): Boolean = a.contains(b)
println(contains2(Seq(1,2,3), "four")) // compilation error
// cmd7.sc:1: No implicit Ordering defined for Any.
// val res7 = isMatched(Seq(1,2,3), "s")
^
// Compilation Failed
However, is there a simpler way to achieve the same behaviour as in contains2
? Ordering
context bound confuses me as the method has nothing to do with sorting/ordering at all.
def contains[T](a: Seq[T])(b: T): Boolean = a.contains(b)
. In this case, since b is in a separate argument list, it is not take into account when inferring the type parameter T, in really the already inferred type T is used, as such, ifb
is not of the same type as the elements in the collection, it will not compile. - Additionally, one advice, add the-Xlint:infer-any
flag. – Weixeldef contains2[T: Eq](a: Seq[T], b: T): Boolean = a.exists(Eq[T].eqv(b, _))
with Cats'sEq
, where the constraint is both meaningful and actually used in the operation. (UnfortunatelyAny
has ascala.math.Equiv
instance, so that's not really useful here.) – Gaylord