2

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?

1 Answer 1

4

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("[", ", ", "]")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.