为什么 Scala trait 可以扩展一个类? [英] Why can a Scala trait extend a class?

查看:37
本文介绍了为什么 Scala trait 可以扩展一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 Scala 中的 trait 类似于 Java 中的接口(但 Java 中的接口扩展了其他接口,它们不扩展类).我看到了一个关于特性使用的SO示例,其中特性扩展了一个类.

I see that traits in Scala are similar to interfaces in Java (but interfaces in Java extend other interfaces, they don't extend a class). I saw an example on SO about traits usage where a trait extends a class.

这样做的目的是什么?为什么 trait 可以扩展类?

What is the purpose of this? Why can traits extend classes?

推荐答案

是的,他们可以,扩展 classtrait 限制了 classes 可以扩展 trait - 即,所有混入 traitclasses 必须扩展那个 class>.

Yes they can, a trait that extends a class puts a restriction on what classes can extend that trait - namely, all classes that mix-in that trait must extend that 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
                              ^

这篇关于为什么 Scala trait 可以扩展一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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