문제

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("[", ", ", "]")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top