reikje
reikje

Reputation: 3064

How do i write an implicit Function conversion for a map call in Scala

How do I write an implicit conversion for the code below (simplified)? I understand that you need to convert (Int) => B to (String) => B.

List(1, 2, 3).map { s: String => "_" + s }
// expected: List("_1", "_2", "_3")

Upvotes: 1

Views: 59

Answers (3)

Yasser Ansari
Yasser Ansari

Reputation: 11

 for(s <- List(1, 2, 3)) yield "_" + s 

Is this what you're looking for?

Upvotes: 0

Till Rohrmann
Till Rohrmann

Reputation: 13346

I think Simon's answer works best. In case that you still want to do the implicit conversion the following should do the trick.

implicit def convertFun[B](fun: String => B): (Int => B) = {
  x: Int => fun(x.toString)
}

Upvotes: 4

Fatih Donmez
Fatih Donmez

Reputation: 4347

Actually you don't need, just do it like;

List(1, 2, 3) map { i: Int => "_" + i }

Upvotes: 0

Related Questions