How to get the apply method of a case class

Given the case class, I want to get an apply method.

I can do A.apply _

, but there is a way to get it with just A

Example

scala> case class A(s: String)
defined class A

scala> def f[B, C](h: B => C) = h
f: [B, C](h: B => C)B => C

scala> f(A.apply _)
res0: String => A = <function1>

      

Is it possible to just write f(A)

or something like this

+3


source to share


2 answers


For me in Scala 2.11: works

package sandbox

object ApplyMethod {
  import sandbox.OtherApplyTest.C
  case class A(s: String)

  object B {
    def apply(s: String): A = A(s)
  }

  def D(s: String) = OtherApplyTest.D(s)

  def f[T](h: String => T) = h("hello")

  def g[T, U](h: T => U) = h

  def main(args: Array[String]) {
    println(f(A)) // prints A(hello)
    // println(f(B)) doesn't compile
    println(f(C)) // prints C(hello)
    println(f(D)) // prints D(hello)
    println(g(A)) // prints A
    println(g(C)) // prints C
    println(g(D)) // prints <function1>
    println(f(g(A))) // prints A(hello)
  }
}

object OtherApplyTest {

  case class C(s: String)

  case class D(s: String)
}

      



It looks like what you want to do (as well as how you did it) It may not work in the REPL or in an older version of Scala.

+3


source


I have never come across a situation where Scala views A(...)

otherwise than A.apply(...)

. f(A)

Works just fine in my interpreter :



scala> case class A(s: String)
defined class A

scala> def f[B, C](h: B => C) = h
f: [B, C](h: B => C)B => C

scala> f(A)
res1: String => A = A

      

+2


source







All Articles