简体   繁体   中英

Structural type instead of a trait

I'm quite new to scala and I am working myself trough a tutorial: http://www.cakesolutions.net/teamblogs/2013/08/02/akka-and-spray/

At some point it comes to testing and it tells that one could get over the inheritance requirement by creating a structural type:

ActorSystem fully implements the Core trait. However, I need to implement the Core trait to satisfy the self-type declaration of the CoreActors.

I could have defined Core to be structural type, in which case,I would not have to worry about implementing Core here. If you want to try it out, remove the trait Core { ... } and replace it with

package object core { type Core = { def system: ActorSystem } } Here, the Core type is a structural type, which says that Core is anything which contains the system: ActorSystem member.

And I don't get this - if I don't create a trait core I can not extend from it in CoreActors - I think I've missed something here. The concept of structural types is also new to me.

Structural types cannot be extended. They describe types not in terms of an hierarchy, but in terms of the methods it provides.

So, in the case where you have

type Core = { def system: ActorSystem }

It means that any type which has a method called system that takes no parameters and return an ActoreSystem will also be a Core .

Structural types in Scala, however, are limited in some ways. For one thing, they cannot be recursive (that is, Core could appear in side Core 's definition), which makes them useless, for example, for things like arithmetic operators.

They are also not efficient, since they are implemented through reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM