小编Bru*_*uno的帖子

按名称和按值类型的多态类型推断

我一直坚持使用类型推断问题而且我不确定我是否做错了,编译器中存在错误,或者它是对语言的限制

我创建了一个虚拟示例来显示问题,用例没有意义,但请相信我,我有一个有效的用例

假设我有这个代码

val function: (Int, String) => String = (_, _) => ""

implicit class Function2Ops[P1, P2, R](f: (P1, P2) => R) {
   def printArgs(p1: P1, p2: P2): Unit = println(p1, p2)
}

function.printArgs(1, "foo")
Run Code Online (Sandbox Code Playgroud)

这工作和打印(1,foo) 现在,如果我更改代码(注意副名称参数)

val function: (Int, => String) => String = (_, _) => ""

implicit class Function2Ops[P1, P2, R](f: (P1, P2) => R) {
   def printArgs(p1: P1, p2: P2): Unit = println(p1, p2)
}

function.printArgs(1, "foo")
Run Code Online (Sandbox Code Playgroud)

它会打印出来 (1,MyTest$$Lambda$131/192881625@61d47554)

现在,在这一点上,我可以尝试模式匹配和/或使用TypeTag来提取值,以防万一是一个名字参数,但是,我实际上想要实现的是做这样的事情

trait Formatter[T] {
  def …
Run Code Online (Sandbox Code Playgroud)

scala

8
推荐指数
1
解决办法
122
查看次数

标签 统计

scala ×1