ghi*_*hik 20 generics foreach types scala
我很好奇-什么是通用型的点U
在声明Traversable
的foreach
方法是什么?
def foreach[U](f: A => U): Unit
Run Code Online (Sandbox Code Playgroud)
由于返回类型Function1
是协变的,为什么不能只是:
def foreach(f: A => Any): Unit
Run Code Online (Sandbox Code Playgroud)
?
Pét*_*rök 10
不是马丁奥德斯基foreach
,我只能猜测:-)看看斯卡拉多克,我看到了这个:
/** Applies a function `f` to all elements of this $coll.
*
* @param f the function that is applied for its side-effect to every element.
* The result of function `f` is discarded.
*
* @tparam U the type parameter describing the result of function `f`.
* This result will always be ignored. Typically `U` is `Unit`,
* but this is not necessary.
*
* @usecase def foreach(f: A => Unit): Unit
*/
Run Code Online (Sandbox Code Playgroud)
因此返回类型f
无关紧要,其结果总是被丢弃.对我来说,这表明在这里使用泛型类型参数来标记返回类型只是一个文档的细微之处,说"返回类型可以是任何东西,真的是任何东西,你喜欢".而返回类型Any
可能会向(某些)读者建议对此处适用的函数类型的某种限制.
另一个方面是Scala非常有意识地从头开始设计为通用的.所以 - 对我来说 - 在这里使用泛型类型参数与语言的一般哲学是一致的,而使用Any
- 尽管在技术上可用 - 将是一种绝对非通用的方法,与语言的其余部分不一致.
归档时间: |
|
查看次数: |
871 次 |
最近记录: |