开发者

Scala error: Found List[Char], required List[ScalaObject]

I have this snippet of Scala code:

def prologList(l: List[ScalaObject], sep: String) =
    "[" + (if (l isEmpty) "" else l.reduceLeft(_ + sep + _)) + "]"

def neighbors(s: State) = prologList(trans(s).toList, ", ")
def labels(s: State) = prologList(labeling(s).开发者_开发百科toList, ", ")

The next-to-last line compiles fine, but on the last line I get the error

Found List[Char], required List[ScalaObject]

(labeling has the type Map[State, Set[Char]].)

I'm a bit surprised, since 1) I thought that List[Char] could be seen as a subtype of List[ScalaObject] (as opposed to Java), and 2) the line above the last line compiles! (trans has type Map[State, Set[State]] though...)

The question is obvious, what am I doing wrong, and how do I fix it?


Char is not a subtype of ScalaObject.

At the top you have Any which a super type of everything. You can probably replace ScalaObject with Any and that should make your code compile.

See http://www.scala-lang.org/node/128 for a type hierarchy diagram.

In the REPL you can use the implicitly function to troubleshoot type relationships:

scala> implicitly[Char <:< Any]
res0: <:<[Char,Any] = <function1>

scala> implicitly[Char <:< ScalaObject]
<console>:6: error: could not find implicit value for parameter e: <:<[Char,ScalaObject]
       implicitly[Char <:< ScalaObject]
                 ^

scala> implicitly[List[Char] <:< List[Any]]
res2: <:<[List[Char],List[Any]] = <function1>

scala> implicitly[List[Char] <:< List[ScalaObject]]
<console>:6: error: could not find implicit value for parameter e: <:<[List[Char],List[ScalaObject]]
       implicitly[List[Char] <:< List[ScalaObject]]

Edit: by the way, do you know about mkString?

trans(s).mkString("[", ", ", "]")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜