在Scala 中,是否可以在不实际调用其名称的情况下实例化对象?
特别是,我有:
val foo = Thing(
Thingy(1,2,3),
Thingy(4,5,6)
)
我想知道是否有可能这样称呼它
val foo = Thing(
(1,2,3),
(4,5,6)
)
这是另一种方法:
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))
}
您可以使用从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
}