在Scala中,可以实例化对象而无需实际调用其名称吗?
特别是,我有:
val foo = Thing(
Thingy(1,2,3),
Thingy(4,5,6)
)
我想知道是否可以这样称呼它
val foo = Thing(
(1,2,3),
(4,5,6)
)
最佳答案
您可以使用从Tuple3
到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
}
那么您可以像这样使用它:
import example.Thingy._
val foo = Thing(
(1,2,3),
(4,5,6)
)
如果
Thingy
是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
}