简体   繁体   中英

Scala view bound in collection type

I have a collection of elements that are implicitly convertible to, say, String. How to make it look like an actual collection of Strings?

def foo[A <% String](it: Iterator[A]) = {
  val its: Iterator[String] = ???
}

(I am aware that view bounds are deprecated but let us assume that signature of foo is fixed, overriding a legacy method.)

One solution I could come up with is defining a trivial converter class between Iterator[A] and Iterator[String] , but that could be cumbersome for other collection classes with many abstract methods. Is there a standard way of handling this situation, without significant extra code?

A <% String is just sugar for an implicit A => String

def foo[A](it: Iterator[A])(conv: A => String) = {
  val its: Iterator[String] = it map conv
}

(If you really want to use the <% syntax you can obtain the function within the block using implicitly[A => 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM