How to flatten a nested tuple?

前端 未结 3 871
野趣味
野趣味 2020-12-29 05:55

I have a nested tuple structure like (String,(String,Double)) and I want to transform it to (String,String,Double). I have various kinds of nested

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 06:25

    There is no flatten on a Tupple. But if you know the structure, you can do something like this:

    implicit def flatten1[A, B, C](t: ((A, B), C)): (A, B, C) = (t._1._1, t._1._2, t._2)
    implicit def flatten2[A, B, C](t: (A, (B, C))): (A, B, C) = (t._1, t._2._1, t._2._2)
    

    This will flatten Tupple with any types. You can also add the implicit keyword to the definition. This works only for three elements. You can flatten Tupple like:

    (1, ("hello", 42.0))   => (1, "hello", 42.0)
    (("test", 3.7f), "hi") => ("test", 3.7f, "hi")
    

    Multiple nested Tupple cannot be flatten to the ground, because there are only three elements in the return type:

    ((1, (2, 3)),4)        => (1, (2, 3), 4)
    

提交回复
热议问题