2013-05-10 100 views
5

下一个代码斯卡拉 - 修真类型推断

def f(chars: List[Char]): List[List[Char]] = chars match { 
    case Nil => List(Nil) 
    case x :: xs => for { 
     v <- f(xs) 
    } yield List(x) :: v 
    } 

提供错误消息

- type mismatch; found : List[List[Any]] required: List[List[Char]] 

请帮助我理解为什么“的”选择了这里最普遍的,而不是任何的字符?我应该阅读什么语言规范的主题?谢谢。

回答

10

结果,你是yieldingList[List[List[Char]]]List[List[Char]]的混合。斯卡拉upcasts到List[List[Any]]。对于你的情况下,或者在下面的会做的工作:

scala> def f(chars: List[Char]): List[List[Char]] = chars match { 
    |  case Nil => List(Nil) 
    |  case x :: xs => for { 
    |  v <- f(xs) 
    |  } yield x :: v 
    | } 
f: (chars: List[Char])List[List[Char]] 

scala> def f(chars: List[Char]): List[List[Char]] = chars match { 
    |  case Nil => List(Nil) 
    |  case x :: xs => for { 
    |  v <- f(xs) 
    |  } yield List(x) ++ v 
    | } 
f: (chars: List[Char])List[List[Char]] 
6

的问题是List(x) - 它需要x

首先,v遍历f(xs)的结果,f返回List[List[Char]]。这意味着结果将是List[X],其中X是由yield返回的类型。

v的类型是List[Char],因为它遍历了f(xs)的内容。所以我们必须找出List(x) :: v的类型,这是List[Char]上的List[Char]。它是而不是连接它们:它将列表添加到仅包含字符的列表中。结果列表将包含CharList[Char]

由于同时满足是Any的唯一类型,然后XAny和的结果为-理解List[Any]