invictus
invictus

Reputation: 81

what is apply method in Scala, especially used in type definition

I know that apply method is syntactic sugar when used in companion object. However, what is apply method for when it is used in type definition just like below?

type Applyn = {
    def apply[A](f: A=>A, n: Int, x: A): A
}

Is there a deference between this sentence? As I guess, this sentence is used for assigning generic function value to Applyn.

For example, by using above sentence, we can make

(Int=>Int, Int, Int)=>Int

(String=>String, Int, String)=>String

etc., into only a single type Applyn.

Is this correct?

Upvotes: 1

Views: 333

Answers (1)

puhlen
puhlen

Reputation: 8519

What you are looking is a structural type. It doesn't refer to any specific type but any type that has a method apply[A](f: A=>A, n: Int, x: A): A. Functions have an apply method, so a function with the correct signature applies, but it's also possible to create types that have that apply method that are not functions. Imagine the following.

object NotAFunction {
  def apply[A](f: A=>A, n: Int, x: A): A = {...}
}

This object doesn't extend Function, so it is not a function but it still satisfies the structural type requirement.

Structural types provide a nice syntax but they are very slow, so they should be avoided where possible, especially in performance critical code.

Upvotes: 1

Related Questions