2

与えられた:

case class Thing(a:Int, b:String, c:Double)

val v = Vector(1, "str", 7.3)

魔法のように作成するものが欲しい:

Thing(1, "str", 7.3)

そのようなものは存在しますか(任意のサイズのもの)?

4

3 に答える 3

3

初めて 2.10 の実験的な反射機能に足を踏み入れました。したがって、ほとんどこのアウトラインhttp://docs.scala-lang.org/overviews/reflection/overview.htmlに従って、私はこれを思いつきました:

import scala.reflect.runtime.{universe=>ru}

case class Thing(a: Int, b: String, c: Double)

object Test {
  def main(args: Array[String]) {
    val v = Vector(1, "str", 7.3)
    val thing: Thing = Ref.runtimeCtor[Thing](v)
    println(thing) // prints: Thing(1,str,7.3)
  }
}

object Ref {
  def runtimeCtor[T: ru.TypeTag](args: Seq[Any]): T = {
    val typeTag = ru.typeTag[T]
    val runtimeMirror = ru.runtimeMirror(getClass.getClassLoader)

    val classSymbol = typeTag.tpe.typeSymbol.asClass
    val classMirror = runtimeMirror.reflectClass(classSymbol)

    val constructorSymbol = typeTag.tpe.declaration(ru.nme.CONSTRUCTOR).asMethod
    val constructorMirrror = classMirror.reflectConstructor(constructorSymbol)
    constructorMirrror(args: _*).asInstanceOf[T]
  }
}

メイン メソッド内にケース クラスがある場合、これはコンパイルされないことに注意してください。タイプタグが非インナーケースクラスに対してのみ生成できるかどうかはわかりません。

于 2013-02-09T06:24:26.270 に答える
1

コンパイル時のエラーで機能するソリューションを取得できるかどうかはわかりませんが、これはマッチングを使用した私のソリューションです。

case class Thing(a: Int, b: String, c: Double)
def printThing(t: Thing) {
  println(t.toString)
}

implicit def vectToThing(v: Vector[Any]) = v match {
  case (Vector(a: Int, b: String, c: Double)) => new Thing(a, b, c)
}

val v = Vector(1, "str", 7.3) // this is of type Vector[Any]
printThing(v) // prints Thing(1,str,7.3)
printThing(Vector(2.0, 1.0)) // this is actually a MatchError

この「モノ」変換には実際の目的がありますか、それとも Vector[Any] の代わりに Tuple3[Int,String,Double] を使用しますか?

于 2013-02-09T08:25:45.607 に答える
0

あなたの質問から、あなたがそれを何に使うのかは明らかではありません。Thing と呼ばれるものは、実際には HList または KList である可能性があります。HListは、「任意の長さのタプル」である異種リストの略です。

ケースクラスのように振る舞うために「unnapply」または「unapplySeq」メソッドを追加するのがどれほど難しいかはわかりません。

私はそれらの経験がほとんどありませんが、ここで良い説明を見つけることができます: http://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala/

これが必要なものでない場合は、達成したいことをお知らせください。

于 2013-02-09T12:25:52.380 に答える