diff options
author | Andy <andys8@users.noreply.github.com> | 2017-07-04 20:21:45 +0200 |
---|---|---|
committer | ven <vendethiel@hotmail.fr> | 2017-07-04 20:21:45 +0200 |
commit | 84c35749189d0d9d9f5b72036dd47780c41bf7c7 (patch) | |
tree | 69c38ec2122dda8cd798f377d80a45934ad2f11e | |
parent | 362135e6bc78a48acb8610b9956d87193680c5cb (diff) |
[scala/en] Add traits in objects chapter (#2760)
* [scala/en] Add traits in objects chapter
* [scala/en] Traits: Describe traits keywords
-rw-r--r-- | scala.html.markdown | 46 |
1 files changed, 45 insertions, 1 deletions
diff --git a/scala.html.markdown b/scala.html.markdown index 5eb94986..78053b40 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -460,8 +460,52 @@ val otherGeorge = george.copy(phoneNumber = "9876") // And many others. Case classes also get pattern matching for free, see below. +// Traits +// Similar to Java interfaces, traits define an object type and method +// signatures. Scala allows partial implementation of those methods. +// Constructor parameters are not allowed. Traits can inherit from other +// traits or classes without parameters. + +trait Dog { + def breed: String + def color: String + def bark: Boolean = true + def bite: Boolean +} +class SaintBernard extends Dog { + val breed = "Saint Bernard" + val color = "brown" + def bite = false +} + +scala> b +res0: SaintBernard = SaintBernard@3e57cd70 +scala> b.breed +res1: String = Saint Bernard +scala> b.bark +res2: Boolean = true +scala> b.bite +res3: Boolean = false + +// A trait can also be used as Mixin. The class "extends" the first trait, +// but the keyword "with" can add additional traits. + +trait Bark { + def bark: String = "Woof" +} +trait Dog { + def breed: String + def color: String +} +class SaintBernard extends Dog with Bark { + val breed = "Saint Bernard" + val color = "brown" +} -// Traits coming soon! +scala> val b = new SaintBernard +b: SaintBernard = SaintBernard@7b69c6ba +scala> b.bark +res0: String = Woof ///////////////////////////////////////////////// |