Could this be simplified?

Referring to https://stackoverflow.com/a/464632/169

The core of complexity is illustrated in one way:

implicit def traversableToFilterOps[CC[X] <: Traversable[X], T] (xs: CC[T])(implicit witness: CC[T] <:< TraversableLike[T,CC[T]]) = new MoreFilterOperations[CC[T], T](xs) 

With two questions:

  • Is there a way to give the compiler a hint that Map matches the signature CC[X] <: Traversable[X] ? I expect it to match as Traversable[Tuple2[_,_]] , but that won't happen. In the end, I had to write a second method accepting CC[KX,VX] <: Map[KX,VX] , but it feels superfluous.

  • witness: CC[T] <:< TraversableLike[T,CC[T]] also seems redundant given the parameter of the first type, I feel this is related to the type of Traversable and should always be true for any possible subclass or value of X , therefore there should be no reason to explicitly demand him as a witness.

If I test this using the existential type in REPL, then the compiler seems to agree with me:

 scala> implicitly[Traversable[X] <:< TraversableLike[X,Traversable[X]] forSome { type X }] res8: <:<[Traversable[X],scala.collection.TraversableLike[X,Traversable[X]]] forSome { type X } = <function1> 

So, is there a way to end the pattern?

+4
source share
1 answer

I am a Scala noob, so please do not shoot me if this does not help.

Assuming this:

 class MoreFilterOperations[Repr <% TraversableLike[T,Repr], T] (xs: Repr) {} 

Something like this work?

 // t2fo is short for traversableToFilterOps implicit def t2fo[Repr <% TraversableLike[T, Repr], T](xs: Repr) = new MoreFilterOperations[Repr, T](xs) // m2fo is short for mapToFilterOps implicit def m2fo[Repr <% Map[K, V] <% TraversableLike[(K,V), Repr], K, V] (xs: Repr) = new MoreFilterOperations[Repr, (K, V)](xs) 

This should work because (according to the book I programmed by Scala, p264), the following method definition with an evaluation of the form:

 def m [A <% B](arglist): R = ... 

This is the same as the definition of this method:

 def m [A](arglist)(implicit viewAB: A => B): R = ... 
+1
source

Source: https://habr.com/ru/post/1340293/


All Articles