/** 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 =>
}
Run Code Online (Sandbox Code Playgroud)
当我在scala中检查Future的源代码时,我无法理解为什么self:Runnable => above compiles.我知道symbol =>可以在方法参数中用作名字调用,也可以用来定义函数.上面的代码似乎定义了一个函数,但它让我很困惑.
ghi*_*hik 11
此语法表示显式类型的自引用.它本质上意味着任何扩展OnCompleteRunnable也必须扩展Runnable.
您可能想知道它与普通继承有何不同:
trait OnCompleteRunnable extends Runnable
Run Code Online (Sandbox Code Playgroud)
简而言之,不同之处在于自键型引用只是一种类型约束.它不建立子类型关系,因此OnCompleteRunnable无法实现或覆盖任何内容Runnable.所以它就像一种较弱的继承形式.