I have code similar to the following, where I have a function that takes List [TypeA], and I want to be able to call it using List [TypeB], where I have an implicit conversion from TypeA to TypeB.
I have an example code that works when I call a method with a List string, but does not work if the list is first assigned to a variable.
Here is the code that works:
class Person(val name: String) implicit def stringToPerson(str: String) : Person = new Person(str) def printAll(list: List[Person]) { list.foreach(person => println("Person: " + person.name)) } def callIt = { printAll(List("1","2","3")) }
Unfortunately, this does not work if callIt looks like this:
def callIt = { val list = List("1","2","3") printAll(list) }
I get a message that it expects List [Person], but I provide List [String]
In my actual code, I have a list already defined somewhere else, so it doesn't work. What can I do to use the implicit conversion from String to Person and why does it work in the first case, but not in the second?
Side note: it also works if I specify the type of the list and whether this conversion is done:
val list: List[Person] = List("1","2","3")
But then again, this is not what I want.
Do I really need to provide an implicit conversion from List [String] to List [Person]?