元组列表的隐式转换

时间:2019-06-04 21:42:24

标签: scala implicit-conversion implicit

我正在尝试将List[(Int, String)]隐式转换为List[(IntWrap, String)],这会导致TypeMismatch错误。

我尝试了一些其他的转换,这些转换是 List[Int]List[IntWrap]Tuple2[Int, String]Tuple2[IntWrap, String]有效。

case class IntWrap(a : Int)

implicit def int2IntWrap(x: Int) = IntWrap(x)

implicit def int2IntWrapForTuple2(tuple: Tuple2[Int, String])  = (IntWrap(tuple._1), tuple._2)

//Defined few methods
def foo(t : (IntWrap, String)) = println(t._2)

def foo_list(t: List[IntWrap]) = println(t.size)

def foo_list_tuple(t : List[(IntWrap, String)]) = println(t.size)

foo(3 -> "hello") //this works

foo_list(List(1, 2, 3)) //this works

val l :  List[(IntWrap, String)] = List(3 -> "hello")

foo_list_tuple(l) //this works

val l1 = List(3 -> "hello")
foo_list_tuple(l1) //this one doesn't work
//error: type mismatch; found: List[(Int, String)] required: List[(IntWrap, String)]

我该如何做?

1 个答案:

答案 0 :(得分:1)

尝试像这样定义隐式转换

implicit def listOfTupleToListOfIntWrapTuple(l: List[(Int, String)]): List[(IntWrap, String)] =
  l.map(tuple => (IntWrap(tuple._1), tuple._2))