Scala中的apply方法是什么,尤其是在类型定义中使用的方法

编程入门 行业动态 更新时间:2024-10-26 18:25:46
本文介绍了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方法是什么,尤其是在类型定义中使用的方法

本文发布于:2023-11-16 19:39:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是在   方法   定义   类型   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!