2014-07-06 1 views
0

두 개가있을 때 유형 태그를 매치 할 수 있다는 것을 알고 있습니다 만, 객체 중 하나가 "모두"일 때 어떻게 이런 종류의 작업을 수행합니까? 아래 (잘못된) 코드를 수행 할 수있는 방법이 있습니까? 함수 "confirm"은 실행시 유연하게 유지되도록 Any 유형을 사용하도록 설계되었습니다. 당신이"Any"와 일치하는 인스턴스 삭제?

import scala.reflect.runtime.universe._ 

    object TestRun extends App { 


     class Matcher[T:TypeTag] { 

     def confirm(x:Any):Boolean {  //I don't want to add paramaters to this, must remain Any 
      val myTT = implicitly[TypeTag[T]] 
      x.isInstanceOf [myTT.tpe] // return an answer? 
     } 


     } 

     val m =new Matcher[Int] 
//example of the output I would expect  
     m.confirm(44) //true 
     m.confirm("test") //false 

     val m2 =new Matcher[Seq[String]] 
     m2.confirm(Seq("A","B","C") //true 


    } 

답변

0

당신이에 구축 할 수 있습니다 감사합니다이 기본적으로 작동

def confirm(x: Any): Boolean = { 
    val myTT = implicitly[TypeTag[T]] 
    println(x.getClass) 
    println(myTT.mirror.runtimeClass(myTT.tpe)) 

    // Compiles, but only exact matches 
    //x.getClass == myTT.mirror.runtimeClass(myTT.tpe) 

    // Better, but not perfect 
    myTT.mirror.runtimeClass(myTT.tpe).isAssignableFrom(x.getClass) 
} 

하지만

  • 당신은 INT/java.lang.Integer의 등을 처리하기 위해 추가 코드를 추가해야합니다. al.
  • 요소의 컬렉션/컨테이너 등의 유형을 처리하는 코드를 추가해야 할 수 있습니다. 해당 유형이 지워졌기 때문에 위의 비교에서 고려하지 않았을 수 있습니다.
관련 문제