Reputation: 505
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)
)
Upvotes: 3
Views: 373
Reputation: 22595
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
}
Upvotes: 2
Reputation: 22439
Here's another approach:
case class Thingy(a: Int, b: Int, c: Int)
case class Thing(x: Thingy, y: Thingy)
object Thing {
def apply(t1: Tuple3[Int, Int, Int], t2: Tuple3[Int, Int, Int]): Thing =
Thing(Thingy(t1._1, t1._2, t1._3), Thingy(t2._1, t2._2, t2._3))
}
Upvotes: 4