Scala Implicit’s Passing / Conversions

May - 30 2016 | By

package Training

import org.scalatest.{Matchers, FlatSpec}

object ObjectType {
  final val Original : String = "Original"
  final val New : String = "New"
}


case class OriginalObject(
                        name: String,
                        age: Integer,
                        location : String,
                        ObjectType : String =  Training.ObjectType.Original
)


case class NewObject(
                      newName: String,
                      newAge: Integer,
                      newLocation : String,
                      ObjectType :String =  Training.ObjectType.New
)



object Converter {
  implicit def OriginalObject_To_NewObject(a: OriginalObject): NewObject =
    NewObject(
      newName = a.name,
      newAge = a.age,
      newLocation = a.location
    )
}

class Implicits  extends FlatSpec
  with Matchers {

  //need to import our converter
import Training.Converter._

  def OnlyPrintNewObjects(newObject: NewObject) {
    println("OnlyPrintNewObjects = "+newObject.toString())
  }


  def printImplicitObjects()(implicit newObject: NewObject) {
    println("printImplicitObjects = "+newObject.toString())
  }




  it should "print a new object implicitly" in {

    // create a original Object
    val originalObj = new OriginalObject("Stephen", 33, "Ireland")

    //send that object to our printer and it will auto-convert to a New Object
    OnlyPrintNewObjects(originalObj)
  }



  it should "pass an object implicitly to a function" in {
    // create a original Object
    implicit val newObj = new NewObject("Stephen", 33, "Ireland")

    //send that object to our printer implicitly
    printImplicitObjects()
  }
}




and this will print out
OnlyPrintNewObjects = NewObject(Stephen,33,Ireland,New)
printImplicitObjects = NewObject(Stephen,33,Ireland,New)

Comments are closed. Please see front page on how to contact me