为什么特征是可实例化的? [英] Why are traits instantiable?

查看:51
本文介绍了为什么特征是可实例化的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Scala 中的 trait 类似于 Java 中的接口,只是方法允许有一个实现.此外,与 Scala 类相比,您不能向它们传递构造参数.

As far as I've learned, traits in Scala are similar to interfaces in Java except methods are allowed to have an implementation. Also, in contrast to Scala classes, you can't pass them arguments for construction.

到目前为止,一切都很好.但是为什么我可以实例化它们呢?真的,我看不出有什么理由允许这样做.

So far, so good. But why am I allowed to instantiate them? Really, I don't see a good reason to allow this.

推荐答案

您并没有真正实例化它们.当您与 Java 进行比较时,让我们更深入地研究它.您可以在 Java 中从抽象类或接口构建匿名类.在 Scala 中几乎相同:

You don't really instantiate them. As you drew a parallel with Java, let's go further into it. You are able in Java to build a Anonymous class out of an abstract class or of an Interface. It is almost the same in Scala:

scala> trait A
defined trait A

scala> new A {}
res0: A = $anon$1@5736ab79

请注意,当您从特征创建对象时,花括号是必需的.例如,你不能这样做:

Note that the curly braces are mandatory when you create an object from a trait. For example, yon cannot do:

scala> new A
<console>:9: error: trait A is abstract; cannot be instantiated
              new A
              ^

虽然它非常适合一个类:

While it would works perfectly for a class:

scala> class B
defined class B

scala> new B
res2: B = B@213526b0

当然,如果你的 trait 中的某些元素没有实现,你需要在创建对象时实现它们:

Of course if some elements in your trait are not implemented, you need to implement them when you create the object:

scala> trait C {def foo: Int}
defined trait C

scala> new C {}
<console>:9: error: object creation impossible, since method foo in trait C of type => Int is not defined
              new C {}
                  ^

scala> new C {def foo = 42}
res4: C = $anon$1@744957c7

这篇关于为什么特征是可实例化的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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