Skip to content

Scala 35 class composition with traits #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.baeldung.scala.classcompositionwithtraits

import com.baeldung.scala.classcompositionwithtraits.CarTraits.{Car, Printable}

object CarTraits {

/**
Expand All @@ -22,6 +20,14 @@ object CarTraits {
/**
* Another trait to be mixed into the class
*/
trait SimpleMarshaller extends Car {
def toJson: String = s"{${"\"model\""}:$model," +
s"\n${"\"horsePower\""}:$horsePower}"
}

/**
* Another trait with self-type to be mixed into the class
*/
trait Marshaller {
self: Car =>
def toJson = s"{${"\"model\""}:$model," +
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package com.baeldung.scala.classcompositionwithtraits

import com.baeldung.scala.classcompositionwithtraits.CarTraits._
import org.scalatest.{Matchers, WordSpec}

/**
* @author Sergey Ionin
*/

class TraitsTest extends WordSpec with Matchers {

import com.baeldung.scala.classcompositionwithtraits.CarTraits._
class CarTraitsTest extends WordSpec with Matchers {

"Class that extends Car" should {
"inherit abstract class fields" in {
Expand All @@ -28,6 +27,14 @@ class TraitsTest extends WordSpec with Matchers {
}
}

"Classes that extends Car with SimpleMarshaller" should {
"inherit abstract class fields and methods" +
"and be marshallable" in {
val bmw0 = new BMW0("F15", 309) with SimpleMarshaller
bmw0.toJson shouldBe "{\"model\":F15,\n\"horsePower\":309}"
}
}

"Classes that extends Car with Marshaller" should {
"inherit abstract class fields and methods" +
"and be marshallable" in {
Expand Down