Is there anything in Scala like a view bound but which can match subtypes?
Since views in Scala do not chain, I currently have the following:
implicit def pimpIterable[A, I[_]](x: I[A])(implicit f: I[A] => Iterable[A]) =
new { def mylength = x.size }
to let me write:
Array(1,2,3).mylength
Seq(1,2,3).mylength
The above form seems necessary since if I try to simplify my function signature with something like:
implicit def pimpIterable[A, I <% Iterable[A]](x: I) =
new { def mylength = x.size }
then the implicit conversion won't work for Arrays since there is no direct view from Array to Iterable (only to a subclass of Iterable, which the first form is able to find).
This also forces all other short-hands to be written out in long form as well. What could have been:
implicit def pimpIterable[A: Scalar, I <% Iterable[A]](x: I) = ...
must now be written as:
implicit def pimpIterable[A, I[_]](x: I[A])(implicit f: I[A] => Iterable[A], m: Scalar[A]) = ...
Is there a Better Way?
There are two problems with the view bound signature. First, Iterable
doesn't have length
, only size
. Next, I
is not a type cosntructor. So, fixing both, the signature is:
implicit def pimpIterable[A, I <% Iterable[A]](x: I) = new { def mylength = x.size }
This is proper. If you parameterize I
, it will exclude types such as BitSet
and String
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.