Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a List[A] into a List[B] using an implicit conversion

Tags:

scala

scalaz

I have the following use case which occurs often in my code:

  • A Collection[A]
  • An implicit conversion A to B

and I want to obtain a collection of B. I can use implicitly like the following:

  case class Items(underlying:List[B])
  import B._
  def apply(a:List[A]):Items = {
    val listOfB= a.map {implicitly[A=>B]}
    Items(listOfB)
  }

What is the most elegant way to do that in Scala, maybe with the help of Scalaz of doing the same?

Edit: the goal of my question is to find an idiomatic way, a common approach among libraries/developers. In such a sense developing my own pimp-my-library solution is something I dislike, because other people writing my code would not know the existence of this conversion and would not use it, and they will rewrite their own. I favour using a library approach for this common functions and that's why I am wondering whether in Scalaz it exists such a feature.

like image 336
Edmondo1984 Avatar asked Feb 18 '13 17:02

Edmondo1984


1 Answers

It's pretty straightforward if you know the types. First implicit conversion from A to B:

implicit def conversion(a: A): B = //...

then you need implicit conversion from List[S] to List[T] where S and T are arbitrary types for which implicit conversion from S to T exists:

implicit def convList[S, T](input: List[S])(implicit c: S => T): List[T] = 
   input map c

This should then work:

val listOfA: List[A] = //...
val listOfB: List[B] = listOfA

which is resolved by the compiler to:

val listOfB: List[B] = convList(listOfA)(conversion)

where S is A and T is B.

like image 164
Tomasz Nurkiewicz Avatar answered Sep 18 '22 23:09

Tomasz Nurkiewicz