복붙노트

[SCALA] 타입에서 TypeTag을 얻기?

SCALA

타입에서 TypeTag을 얻기?

나는 TPE 방법을 사용하여 TypeTag [A]에서 유형을 얻을 수 있습니다. 그러나 나는 또한 유형에서 유형 태그를 복구 할 수 있습니다?

import scala.reflect.runtime.{universe => ru}
import ru.{Type, TypeTag}

def forward[A](implicit tt: TypeTag[A]): Type = tt.tpe

def backward(t: Type): TypeTag[_] = ???

그 이유는 내가지도에 키와 같은 용도의 형 태그,하지만 어느 시점에서 난 단지 유형을 가지고 태그를 떨어졌다 API를 가지고있는.

해결법

  1. ==============================

    1.것이 가능하다:

    것이 가능하다:

    import scala.reflect.runtime.universe._
    import scala.reflect.api
    
    val mirror = runtimeMirror(getClass.getClassLoader)  // whatever mirror you use to obtain the `Type`
    
    def backward[T](tpe: Type): TypeTag[T] =
      TypeTag(mirror, new api.TypeCreator {
        def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
          if (m eq mirror) tpe.asInstanceOf[U # Type]
          else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
      })
    
    assert(backward[String](forward[String]) == typeTag[String])
    
  2. from https://stackoverflow.com/questions/27887386/get-a-typetag-from-a-type by cc-by-sa and MIT license