如何在元组之间应用隐式转换? [英] How to apply implicit conversions between tuples?

查看:45
本文介绍了如何在元组之间应用隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用柯里化/元组作为将参数传递给函数的替代方法.在这段旅程中,我遇到了一些困难.

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:

给定(REPL 示例):

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

//这行得通——显然

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:为什么元组转换不起作用?(我期待答案是这样的:需要的是 Tuple2[Cont,Cont] 到 Tuple2[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)

问题 2:有哪些选项可以使此类转换有效?请记住,我想要一个 N 元组的解决方案,因此在这种情况下,将特定的 Tuple2 定义为 Tuple2 并不是一个很好的解决方案.AFAIK,磁铁图案的工作原理类似,所以我希望有办法.

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.

推荐答案

Q1:为什么元组转换不起作用?(我期待答案是这样的:需要的是 Tuple2[Cont,Cont] 到 Tuple2[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)

是的,你说得对.

我有哪些选择可以使此类转换有效?

What are my options to have such conversion working?

你可以这样做:

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

这篇关于如何在元组之间应用隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆