CCh CCh - 1 month ago 5
Scala Question

About using scala def apply method

val B = new {
def apply : { val a : Int } => { val b : String ; val c : Int } =
x => new { val b = "Hi" ; val c = 0 }
}


I can't understand this code.

What does it doing?

And how can I use apply of B. It seems B doesn't have b or c..

Answer

Compiles just fine here.

scala> val B = new {
    |   def apply : { val a : Int } => { val b : String ; val c : Int } =
    |     x => new { val b = "Hi" ; val c = 0 }
    | }
B: AnyRef{def apply: AnyRef{val a: Int} => AnyRef{val b: String; val c: Int}} = $anon$1@464bee09

The signature is quite clear, however something you'll have to get used to.

AnyRef

an anonymous object. Similar to java Object

  {def apply: AnyRef{val a: Int} => AnyRef{val b: String; val c: Int}}

however, you still have the signature available via structural typing. I normally wouldn't recommend that, it uses reflection at runtime, which makes the method call a bit slow.

  def apply: AnyRef{val a: Int} => AnyRef{val b: String; val c: Int}

It returns a =>, also known as Function1, which is short for a function object that takes one argument. Here it takes an argument of type AnyRef{val a: Int} and returns an object of type AnyRef{val b: String; val c: Int}.

The same comment as above applies for the structural typing nature.

How I would recommend writing this code:

case class Foo(b: String, c: Int)
val B: Int => Foo = { x => Foo("Hi", 0) }
Comments