Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- GRPC: make high-throughput client in Java/Scala
- Setting up multiple test folders in a SBT project
- Testing request with CSRF Token in Play framework
- Run project with java options via sbt
I am quoting from the website of the book Programming in Scala, First Edition and more specifically the section called "To trait, or not to trait?" from Chapter 12.
There is a bit more information in the above link regarding traits and I suggest you read the full section. I hope this helps.
Traits are useful for mixing functionality into a class. Take a look at http://scalatest.org/. Note how you can mix in various domain-specific languages (DSL) into a test class. look at the quick start guide to look at some of the DSL's supported by Scalatest ( http://scalatest.org/quick_start )
The short answer is that you can use multiple traits -- they are "stackable". Also, traits cannot have constructor parameters.
Here's how traits are stacked. Notice that the ordering of the traits are important. They will call each other from right to left.
This site gives a good example of trait usage. One big advantage of traits is that you can extend multiple traits but only one abstract class. Traits solve many of the problems with multiple inheritance but allow code reuse.
If you know ruby, traits are similar to mix-ins
Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods.
Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods.
In contrast to classes, traits may not have constructor parameters. Traits are like classes, but which define an interface of functions and fields that classes can supply concrete values and implementations.
Traits can inherit from other traits or from classes.