强制Scala特性实施某种方法 [英] Force Scala trait to implement a certain method

查看:84
本文介绍了强制Scala特性实施某种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以指定特征必须提供方法的具体实现?

Is there a way to specify that a trait has to provide a concrete implementation of a method?

给出一些混入

class A extends B with C {
  foo()
}

如果ABC中的任何一个实现了foo(),则程序将编译.但是,例如,如何强制B包含foo的实现?

The program will compile if either of A, B, or C implements foo(). But how can we force, for example, B to contain foo's implementation?

推荐答案

您可以执行以下操作:

class A extends B with C {
  super[B].foo()
}

这仅在B 实现 foo时编译.请谨慎使用,因为(可能)引入了一些不直观的耦合.此外,如果A覆盖foo,仍将调用Bfoo.

This will only compile if B implements foo. Use with caution though as it (potentially) introduces some unintuitive coupling. Further, if A overrides foo, still B's foo will be called.

一个恕我直言的有效用例是解决冲突:

One IMHO valid use case is conflict resolution:

trait B { def foo() = println("B") }
trait C { def foo() = println("C") }
class A extends B with C {
  override def foo() = super[B].foo()
}

如果要确保B 声明 foo,可以使用类型说明:

If you want to make sure B declares foo, you can use type ascription:

class A extends B with C {
  (this:B).foo()
}

仅在B 声明 foo时才编译(但是可以在CA中实现).

This will only compile if B declares foo (but it might be implemented in C or A).

这篇关于强制Scala特性实施某种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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