It looks like you're trying to apply your function to the inner most item of the collection regardless of how deep you're values are nested (in this case, List[T]
and List[List[T]]
).
trait CanMapInner[WrappedV, WrappedB, V, B] {
def mapInner(in: WrappedV, f: V ⇒ B): WrappedB
}
// simple base case (no nesting involved).
implicit def simpleMapper[V, B] = new CanMapInner[V, B, V, B] {
def mapInner(in: V, f: (V) ⇒ B): B = f(in)
}
// drill down one level of "List".
implicit def wrappedMapper[V, B, InnerV, InnerB](implicit innerMapper: CanMapInner[InnerV, InnerB, V, B]) =
new CanMapInner[List[InnerV], List[InnerB], V, B] {
def mapInner(in: List[InnerV], f: (V) ⇒ B): List[InnerB] =
in.map(innerMapper.mapInner(_, f))
}
implicit class XXX[WrappedV](list: List[WrappedV]) {
def xxx[V, B, WrappedB](f: V ⇒ B)(implicit mapper: CanMapInner[WrappedV, WrappedB, V, B]) = {
list.map(inner ⇒ mapper.mapInner(inner, f))
}
}
Adapted from qmajor's solution for Map
.
Usage:
def f(i: Int): String = "Hello " + i.toString
val source1: List[List[Int]] = List(List(1, 2), List(3, 4))
val source2: List[Int] = List(1, 2)
val result1: List[List[String]] = source1.xxx(f)
val result2: List[String] = source2.xxx(f)
Console println source1
// > List(List(1, 2), List(3, 4))
Console println source2
// > List(1, 2)
Console println result1
// > List(List(Hello 1, Hello 2), List(Hello 3, Hello 4))
Console println result2
// > List(Hello 1, Hello 2)
I changed your f
function for demo purposes.