我看到 Scala 中的特质与 Java 中的接口相似(但在 Java 中,接口扩展其他接口,它们不扩展类)。我在 SO 上看到了一个关于特质使用的示例,其中一个特质扩展了一个类。
这是为什么呢?为什么特质可以扩展类?
我看到 Scala 中的特质与 Java 中的接口相似(但在 Java 中,接口扩展其他接口,它们不扩展类)。我在 SO 上看到了一个关于特质使用的示例,其中一个特质扩展了一个类。
这是为什么呢?为什么特质可以扩展类?
可以,一个扩展 class
的 trait
会对可以扩展该 trait
的 classes
施加限制——即,所有混入该 trait
的 classes
必须扩展该 class
。
scala> class Foo
defined class Foo
scala> trait FooTrait extends Foo
defined trait FooTrait
scala> val good = new Foo with FooTrait
good: Foo with FooTrait = $anon$1@773d3f62
scala> class Bar
defined class Bar
scala> val bad = new Bar with FooTrait
<console>:10: error: illegal inheritance; superclass Bar
is not a subclass of the superclass Foo
of the mixin trait FooTrait
val bad = new Bar with FooTrait
^
trait FooTrait { self:Foo => }
。什么情况下会使用其中一种技术而不是另一种? 回答:当您需要确保混入特质的类都满足某些条件时,可以使用带有自身类型约束的技术。另一方面,如果您只想确保特质被用于与指定类型兼容的类,则可以使用类型参数的方式来限制。选择哪种技术取决于您的具体需求和实际场景。 - AmigoNico