2016-04-23 70 views
2

我在使用反射比较两种类型之间的'兼容性'(实际上我在写一个宏)时遇到问题。例如,我想要允许Vector[Int] === List[Int]。现在我知道了general approach。但问题是我不能在这种情况下获取类型构造函数参数:获取适当的类型构造函数参数为“精致”类型

import scala.reflect._ 
import runtime.universe._ 

typeOf[List[Int]].typeArgs        // List(Int) OK 
typeOf[List[Int] with java.io.Serializable].typeArgs // List() FAIL 

为什么这是一个问题?

def test[A, B >: A](a: A, b: B)(implicit tt: TypeTag[B]) = { 
    println(s"tt = $tt") 
    typeOf[B].typeArgs 
} 

现在这个工程:

test(List(1, 2, 3), List(1, 2, 3)) // List(Int) 

但这并不:

test(Vector(1, 2, 3), List(1, 2, 3)) // List() 

回答

0

一个可以使用名为RefinedType的提取:

def test[A, B >: A](a: A, b: B)(implicit tt: TypeTag[B]): List[List[Type]] = { 
    val all = typeOf[B] match { 
    case RefinedType(parents, scope) => parents.map(_.typeArgs) 
    case x => x.typeArgs :: Nil 
    } 
    all.filter(_.nonEmpty) 
} 

test(List(1, 2, 3), List(1, 2, 3)) 
test(Vector(1, 2, 3), List(1, 2, 3)) 

然后一个仍然有以某种方式鳍d调整父母的策略。 (我现在正在测试所有组合)。

相关问题