2016-04-23 58 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調整父母的策略。 (我現在正在測試所有組合)。

相關問題