Skip to content

Commit c05199c

Browse files
authored
Add class composition with mixins examples (#99)
1 parent c583bbc commit c05199c

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

scala-core/src/main/scala/com/baeldung/scala/classcompositionwithtraits/CarTraits.scala renamed to scala-core-oop/src/main/scala/com/baeldung/scala/classcompositionwithtraits/CarTraits.scala

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.baeldung.scala.classcompositionwithtraits
22

3-
import com.baeldung.scala.classcompositionwithtraits.CarTraits.{Car, Printable}
4-
53
object CarTraits {
64

75
/**
@@ -22,6 +20,14 @@ object CarTraits {
2220
/**
2321
* Another trait to be mixed into the class
2422
*/
23+
trait SimpleMarshaller extends Car {
24+
def toJson: String = s"{${"\"model\""}:$model," +
25+
s"\n${"\"horsePower\""}:$horsePower}"
26+
}
27+
28+
/**
29+
* Another trait with self-type to be mixed into the class
30+
*/
2531
trait Marshaller {
2632
self: Car =>
2733
def toJson = s"{${"\"model\""}:$model," +

scala-core/src/test/scala/com/baeldung/scala/classcompositionwithtraits/TraitsTest.scala renamed to scala-core-oop/src/test/scala/com/baeldung/scala/classcompositionwithtraits/CarTraitsTest.scala

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
package com.baeldung.scala.classcompositionwithtraits
22

3+
import com.baeldung.scala.classcompositionwithtraits.CarTraits._
34
import org.scalatest.{Matchers, WordSpec}
45

56
/**
67
* @author Sergey Ionin
78
*/
89

9-
class TraitsTest extends WordSpec with Matchers {
10-
11-
import com.baeldung.scala.classcompositionwithtraits.CarTraits._
10+
class CarTraitsTest extends WordSpec with Matchers {
1211

1312
"Class that extends Car" should {
1413
"inherit abstract class fields" in {
@@ -28,6 +27,14 @@ class TraitsTest extends WordSpec with Matchers {
2827
}
2928
}
3029

30+
"Classes that extends Car with SimpleMarshaller" should {
31+
"inherit abstract class fields and methods" +
32+
"and be marshallable" in {
33+
val bmw0 = new BMW0("F15", 309) with SimpleMarshaller
34+
bmw0.toJson shouldBe "{\"model\":F15,\n\"horsePower\":309}"
35+
}
36+
}
37+
3138
"Classes that extends Car with Marshaller" should {
3239
"inherit abstract class fields and methods" +
3340
"and be marshallable" in {

0 commit comments

Comments
 (0)