什么是 Scala 中的 apply 方法,特别是在类型定义中使用 [英] what is apply method in Scala, especially used in type definition

查看:34
本文介绍了什么是 Scala 中的 apply 方法,特别是在类型定义中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆