Scala implicit conversion of a common argument

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]?

+4
source share
1 answer

The reason your source code works is because in printAll(List("1","2","3")) compiler uses type inference to know that Person is needed before it creates the List . This line tells the compiler that it needs List[Person] , which then forces the List() call to return List[Person] , which forces the parameters of this call to be Person, which then forces the implicit conversion from String to Person to be used. Unfortunately, the val list = List("1","2","3") statement val list = List("1","2","3") does not say anything about the need to be of type List[Person]

+4
source

Source: https://habr.com/ru/post/1391964/


All Articles