gpt4 book ai didi

function - 为什么( self : Runnable =>) in scala compiles?

转载 作者:行者123 更新时间:2023-12-02 06:00:46 25 4
gpt4 key购买 nike

/** A marker indicating that a `java.lang.Runnable` provided to `scala.concurrent.ExecutionContext`
* wraps a callback provided to `Future.onComplete`.
* All callbacks provided to a `Future` end up going through `onComplete`, so this allows an
* `ExecutionContext` to special-case callbacks that were executed by `Future` if desired.
*/
trait OnCompleteRunnable {
self: Runnable =>
}

当我查看scala中Future的源代码时,我无法理解为什么上面的self:Runnable =>可以编译。我知道符号 => 可以在方法参数中用作按名称调用,也可以用于定义函数。上面的代码看起来像是在定义一个函数,但它让我感到困惑。

最佳答案

此语法表示一个 explicitly typed self reference .它本质上意味着无论扩展 OnCompleteRunnable 还必须扩展 Runnable

您可能想知道这与普通继承有何不同:

trait OnCompleteRunnable extends Runnable

简而言之,区别在于自类型引用只是一种类型约束。它不建立子类型关系,因此 OnCompleteRunnable 无法实现或覆盖 Runnable 中的任何内容。所以它类似于一种较弱的继承形式。

关于function - 为什么( self : Runnable =>) in scala compiles?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25760344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com