指定应用 eta 扩展的方法的方法签名
Specify the method signature of the method to apply the eta expansion
有没有办法指定我要应用 eta 扩展 的方法的签名?
例如:
val tupleNum = (1L,2L)
case class CaseClass(a:String, b:String)
object CaseClass {
def apply(a: Long, b: Long): CaseClass = new CaseClass(s"${a}", s"${b}")
}
println( (CaseClass.apply _).tupled(tupleNum) )
抛出编译错误:
Error:(9, 29) ambiguous reference to overloaded definition,
both method apply in object CaseClass of type (a: String, b: String)CaseClass
and method apply in object CaseClass of type (a: Long, b: Long)CaseClass
match expected type ?
println( (CaseClass.apply _).tupled(tupleNum) )
顺便说一句:eta 扩展 是使用 _ 的正确术语吗?
- 如果指定签名,则无论如何都必须指定参数类型。
- 如果您已经指定了参数的类型,则可以改用占位符表示法。
这里编译并运行得很好(奇怪的缩进以避免 :paste
模式):
case class C(a: String, b: String); object C {
def apply(a: Long, b: Long): C = C(s"$a", s"$b")
}
val t = (1L, 2L)
println((C.apply(_: Long, _: Long)).tupled(t))
或者更确切地说
println((C(_: Long, _: Long)).tupled(t))
有没有办法指定我要应用 eta 扩展 的方法的签名?
例如:
val tupleNum = (1L,2L)
case class CaseClass(a:String, b:String)
object CaseClass {
def apply(a: Long, b: Long): CaseClass = new CaseClass(s"${a}", s"${b}")
}
println( (CaseClass.apply _).tupled(tupleNum) )
抛出编译错误:
Error:(9, 29) ambiguous reference to overloaded definition,
both method apply in object CaseClass of type (a: String, b: String)CaseClass
and method apply in object CaseClass of type (a: Long, b: Long)CaseClass
match expected type ?
println( (CaseClass.apply _).tupled(tupleNum) )
顺便说一句:eta 扩展 是使用 _ 的正确术语吗?
- 如果指定签名,则无论如何都必须指定参数类型。
- 如果您已经指定了参数的类型,则可以改用占位符表示法。
这里编译并运行得很好(奇怪的缩进以避免 :paste
模式):
case class C(a: String, b: String); object C {
def apply(a: Long, b: Long): C = C(s"$a", s"$b")
}
val t = (1L, 2L)
println((C.apply(_: Long, _: Long)).tupled(t))
或者更确切地说
println((C(_: Long, _: Long)).tupled(t))