Search code examples
scalaimplicit

Scala implicit constructor


Is it possible, in Scala, to instanciate an object without actually calling its name ?

In particular, I have :

val foo = Thing(
  Thingy(1,2,3),
  Thingy(4,5,6)
)

And I wonder if it would be possible to call it like that

val foo = Thing(
  (1,2,3),
  (4,5,6)
)

Solution

  • You can use implicit conversion from Tuple3 to Thingy:

    package example
    
    case class Thingy(v1:Int, v2:Int, v3:Int)
    
    object Thingy {
       implicit def tuple2Thingy(t: Tuple3[Int, Int, Int]) = Thingy(t._1, t._2, t._3)
       //add conversion in companion object
    }
    

    then you can use it like this:

    import example.Thingy._
    
    val foo = Thing(
        (1,2,3),
        (4,5,6)
    )
    

    If Thingy is vararg:

    case class Thingy(v1:Int*)
    
    object Thingy {
       implicit def tuple2ToThingy(t: Tuple2[Int, Int]) = Thingy(t._1, t._2)
       implicit def tuple3ToThingy(t: Tuple3[Int, Int, Int]) = Thingy(t._1, t._2, t._3)
       //etc until Tuple22
    }