问题
I'm experimenting with currying/tupled as an alternative means to pass parameters to a function. In this journey, I'm facing some type difficulties.
I'd like to use implicit conversions to transform a tuple of parameters to the target type. This is what I expect:
Given (REPL example):
case class Cont(value:String) // a simplified container class
val paramTuple = (Cont("One"),Cont("2"))
def operate(s:String, i:Int): String = s+i // my target operation
implicit def contToString(c:Cont): String = c.value
implicit def contToInt(c:Cont): Int = c.value.toInt
//This works - obviously
operate(paramTuple._1, paramTuple._2)
>res4: String = One2
//This is what I want, but doesn't work
(operate _).tupled(params)
<console>:14: error: type mismatch;
found : (Cont, Cont)
required: (String, Int)
Q1: Why the tuple conversion doesn't work? (I'm expecting that an answer to that goes in the lines of: What's required is an implicit conversion between Tuple2[Cont,Cont] to Tuple2[String,Int] but that does not scale up)
Q2: What are my options to have such conversion working? Keep in mind that I'd like to have a solution for an N-tuple, so defining a specific Tuple2 to Tuple2 is not really a good solution in this case. AFAIK, the magnet pattern works similarly, so I hope there's a way.
回答1:
Q1: Why the tuple conversion doesn't work? (I'm expecting that an answer to that goes in the lines of: What's required is an implicit conversion between Tuple2[Cont,Cont] to Tuple2[String,Int] but that does not scale up)
Yes, you've got that right.
What are my options to have such conversion working?
You could do it this way:
implicit def liftImplicitTuple2[A, B, A1, B1](tuple: (A, B))
(implicit f1: A => A1, f2: B => B1): (A1, B1) =
(f1(tuple._1), f2(tuple._2))
implicit def liftImplicitTuple3[A, B, C, A1, B1, C1](tuple: (A, B, C))
(implicit f1: A => A1, f2: B => B1, f3: C => C1): (A1, B1, C1) =
(f1(tuple._1), f2(tuple._2), f3(tuple._3))
// etc for tuples as large as you need
来源:https://stackoverflow.com/questions/23911151/how-to-apply-implicit-conversions-between-tuples