Search code examples
scalascala-placeholder-syntaxeta-expansion

Specify the method signature of the method to apply the eta expansion


Is there a way to specify the signature of the method to which I want to apply the eta expansion?

For example:

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) )

Throws the compilation error:

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) )

BTW: Is eta expansion the right term for the use of _?


Solution

    • If you're specifying the signature, you have to specify the types of arguments anyway.
    • If you're already specifying the types of arguments, you might just use placeholder notation instead.

    This here compiles and runs just fine (weird indentation to avoid :paste mode):

    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))
    

    or rather

    println((C(_: Long, _: Long)).tupled(t))