1

我有以下代码

def sendMoney[T <: MoneyType](fn: T => Future[T], input: T): Unit

就是这样称呼的

case x: Any => (sendMoney(_, _).tupled(x match {
  case c: HoldsMoney => (createHold(_: HoldsMoney), c: HoldsMoney)
  case r: ReserveMoney => (createReserve(_: ReserveMoney), r: ReserveMoney)
})

HoldsMoneyReserveMoney具有MoneyType.

Scala 编译器抛出以下错误。

missing parameter type for expanded function

请注意,如果

x match {
  case c: HoldsMoney => sendMoney(createHold(_: HoldsMoney), c)
  case r: ReserveMoney => sendMoney(createReserve(_: ReserveMoney), r)
}
4

2 回答 2

3

考虑类型

x match {
  case c: HoldsMoney => (createHold(_: HoldsMoney), c: HoldsMoney)
  case r: ReserveMoney => (createReserve(_: ReserveMoney), r: ReserveMoney)
}

is的类型和createHold(_: HoldsMoney)isHoldsMoney => Future[HoldsMoney]的类型。createReserve(_: ReserveMoney)ReserveMoney => Future[ReserveMoney]

因为函数的参数类型是逆变的,所以这两个函数的公共类型只能是Nothing => Future[MoneyType]. 所以整体的类型match(Nothing => Future[MoneyType], MoneyType)不符合sendMoney的参数类型。

所以问题是不可能为sendMoney's 参数的不同组合找到合适的通用类型。

于 2017-01-13T09:59:36.593 回答
0

我认为您的目标是重构参数创建sendMoney并使用tupled. 我猜你的代码缺少部分,为了简单起见删除类型边界。

def sendMoney(fn: (MoneyType) => Future[MoneyType], input: MoneyType): Unit = println("sendMoney")

def createHold(moneyType: MoneyType): Future[MoneyType] = ???
def createReserve(moneyType: MoneyType): Future[MoneyType] = ???

(sendMoney _).tupled(x match {
  case c: HoldsMoney => (createHold, c)
  case r: ReserveMoney => (createReserve, r)
})
于 2017-01-13T10:31:38.527 回答