2017-07-05 7 views
0

次のコードでは、new Box(10), new Box("20")がうまく動作します。しかしnew Box(Seq(20)), new Box(Seq("20")))、 のために私は私が配列[のInt]を印刷することができるように、配列の型パラメータの種類を把握したいと思い、配列[文字列]入れ子型パラメータの型パラメータを調べる方法

 @Test 
     def testClassTag(): Unit = { 
     class Box[T:ClassTag](val data: T) { 
      def printTypeParameter() = { 
      val tag = implicitly[ClassTag[T]].runtimeClass 
      tag match { 
       case _ if tag == classOf[Int] => println("Int") 
       case _ if tag == classOf[String] => println("String") 
       case _ if tag == classOf[Seq[_]] => println("Seq") 
      } 
      } 
     } 
     val boxes = Seq(new Box(10), new Box("20"), new Box(Seq(20)), new Box(Seq("20"))) 
     boxes.foreach(_.printTypeParameter()) 

    } 

答えて

1

それを行うための新しい適切な方法であります

def foo[T : TypeTag](data: T) = typeOf[T] match { 
    case t if t =:= typeOf[Int] => println("Int") 
    case t if t =:= typeOf[String] => println("String") 
    case t if t <:< typeOf[Seq[String]] => println("Seq[String]") 
    // etc 
} 
(あなたはそれをプリントアウトしたい場合、あなたにもこれを行うことができます: TypeTag代わりの ClassTagを使用して

def foo[T : TypeTag](data: T) = println(typeOf[T])` 

それは、SAを行います私のものは、あなたが考えることができるだけでなく、すべての種類を処理します。

+0

回答ありがとうございました! – Tom

1

@ dimaの答えはエレガントなので、タイプパラメータを段階的に検出する別の方法をとっておきます。

@Test 
    def testTypeTag1(): Unit = { 
    class Box[T: TypeTag](val data: T) { 
     def printTypeParameter() = { 
     typeOf[T] match { 
      case t if t =:= typeOf[Int] => println("Int") 
      case t if t =:= typeOf[String] => println("String") 
      case t if t <:< typeOf[Seq[Any]] => { 
      val TypeRef(_, _, Seq(elementType)) = typeOf[T] 
      elementType match { 
       case t if t =:= typeOf[Int] =>println("Seq[Int]") 
       case t if t =:= typeOf[String] =>println("Seq[String]") 
       case _=>println("Seq[Unknown]") 
      } 
      } 
      case _ => println("Unknown") 
     } 
     } 
    } 
    val boxes = Seq(new Box(10), new Box("20"), new Box(Seq(20)), new Box(Seq("20"))) 
    boxes.foreach(_.printTypeParameter()) 
    } 
関連する問題