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

风格不统一 提交于 2019-12-02 10:57:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43388872/what-is-apply-method-in-scala-especially-used-in-type-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!