实例化一个特征是什么意思? [英] What does it mean to instantiate a trait?

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

问题描述

我是 Scala 的新手,在 O'Reilly 的 Programming Scala 书中,作者展示了一些实例化特征的代码.鉴于 trait 有点类似于 Java 中的接口(尽管我知道 trait 在字节码中是作为类实现的),那么实例化一个 trait 意味着什么,什么是合适的用例/设计模式?

例如:

scala>val x = 带有 T2 的新 T1 { type z = String val v: z = "Z" }x: java.lang.Object with T1 with T2{type z = String;def zv: this.z} = $anon$1@9d9347d

解决方案

我对 Scala 也相当陌生,但我认为你上面的例子是创建一个新的匿名对象(就像你可以用 Java 做的那样),然后将 Trait 附加到新的匿名类型.

由于 Scala Traits 可以包含实现代码,因此您基本上可以免费获得 Trait 的行为,假设匿名类满足 Trait 的任何要求(例如设置值或定义抽象"方法).

因此,您在这里所做的不是直接实例化 Trait,而是为 Trait 创建一个合适的对象以将其自身附加到,这样您就可以使用 Trait 的功能,而无需定义扩展 Trait 的类.

这是否回答了您的问题?

I'm new to Scala and in the Programming Scala book from O'Reilly the authors show some code that instantiates a trait. Given that traits are somewhat analogous to interfaces in Java (although I know traits are implemented as classes in the byte code), what does it mean to instantiate a trait, and what would be an appropriate use case / design pattern for this?

E.g.:

scala> val x = new T1 with T2 { type z = String val v: z = "Z" } 
x: java.lang.Object with T1 with T2{type z = String; def zv: this.z} = $anon$1@9d9347d

解决方案

I'm reasonably new to Scala as well, but I think the example that you have above is creating a new anonymous object (like you can do with Java), and then attaching the Trait to the new anonymous type.

Since Scala Traits can contain implementation code, you basically get the behavior of the Trait for free, assuming the anonymous class satisfies any requirements of the Trait (like having values set, or defining "abstract" methods).

So what you are doing here is not instantiating the Trait directly, but rather creating a suitable object for the Trait to attach itself to so you can use the Trait's functionality without needing to define a class that extends the Trait.

Does that answer your question?

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

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