Understanding type conversion/error in Scala in this example -


first, here 3 snippets of code along output on scala 2.10.2

// 1. def one: seq[list[string]] =   seq(list("x")) ++ list(list("x")) println(one) // => list(list(x), list(x)))  // 2. def two: list[list[string]] =   seq(list("x")) ++ list(list("x")) println(two) // => // error: type mismatch; //  found   : seq[list[string]] //  required: list[list[string]] //   seq(list("x")) ++ list(list("x")) // 1 error found  // 3. println(seq(list("x")) ++ list(list("x"))) // => list(list(x), list(x)) 

the main code in 3 snippets same -- seq(list("x")) ++ list(list("x"))

the first , third snippet show (print) type list[list[string]], second snippet, specifies return type list[list[string]] fails compile. first one's return type seq[list[string]] it's printed list[list[string]].

what happening here?

the return type of second snippet list[list[string]], value has type seq[list[string]], exception occurs. list subclass of seq, it's more concrete type. println prints out values have, not types, if want see actual type of expression, print in scala repl:

scala> seq(list("x")) ++ list(list("x")) res5: seq[list[string]] = list(list(x), list(x)) 

see res5 type infered seq[list[string]], value list(list(x), list(x)). list case class automatically overriden tostring method, which, readability overriden compiler.


Comments