2014-11-24 25 views
3

在一個庫中,有一個具有較高主幹類型的類取一個類型參數。我想給它一個類型,需要兩個類型參數,所以我使用type表達式來修復其他參數。使用較高主幹類型時的類型不匹配

但它並不像我所期望的那樣。

代碼減少到這一點:

object Main { 

    class Bar[T[_]] { 
    def bar[A]: Option[T[A]] = None 
    } 

    def foo[A] = { 
    type T[B] = Map[A, B] 
    new Bar[T] 
    } 

    val f: Option[Map[String, Int]] = foo[String].bar[Int] 

} 

我得到一個錯誤編譯(斯卡拉2.11.4)時:

test.scala:12: error: type mismatch; 
found : Option[T[Int]] 
    (which expands to) Option[scala.collection.immutable.Map[A,Int]] 
required: Option[Map[String,Int]] 
    val f: Option[Map[String, Int]] = foo[String].bar[Int] 
               ^
one error found 

爲什麼會出現這類錯誤?

回答

5

類型labmdas應該有所幫助:

class Bar[T[_]] { 
    def bar[A]: Option[T[A]] = None 
    } 

    def foo[A] = { 
    new Bar[({type M[B] = Map[A, B]})#M] 
    } 

    val f: Option[Map[String, Int]] = foo[String].bar[Int] 

但是我不能回答爲什麼類型T沒有在這種情況下工作。

+0

現在你提到它了,我以前見過用於此的那些。 – 2014-11-24 05:16:54