Scala中的apply方法是什么,尤其是在类型定义中使用的方法 [英] what is apply method in Scala, especially used in type definition
问题描述
我知道apply
方法在伴侣对象中使用时是语法糖.
但是,在类型定义中使用apply
方法的方式如下所示?
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
}
这句话之间有区别吗? 我猜想这句话是用来为Applyn分配泛型函数值的.
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
等,仅转换为单一类型Applyn
.
etc., into only a single type Applyn
.
这正确吗?
推荐答案
您正在寻找的是结构类型.它不引用任何特定类型,而是引用具有方法apply[A](f: A=>A, n: Int, x: A): A
的任何类型.函数具有apply方法,因此具有正确签名的函数也适用,但是也可以创建具有非函数的apply方法的类型.想象一下.
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 = {...}
}
该对象没有扩展Function,因此它不是函数,但仍满足结构类型要求.
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.
这篇关于Scala中的apply方法是什么,尤其是在类型定义中使用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!