Scala隐式构造函数

时间:2018-05-05 16:51:59

标签: scala implicit

在Scala中,是否有可能在不实际调用其名称的情况下实例化对象?

特别是,我有:

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

我想知道是否可以这样称呼它

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

2 个答案:

答案 0 :(得分:4)

这是另一种方法:

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))
}

答案 1 :(得分:1)

您可以使用从Tuple3Thingy的隐式转换:

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
}