Scala: Why does isInstanceOf[List[Any]] not work? -
i trying solve problem 7 of 99 scala problems , encountered difficulty in figuring out type of list
can contain type. looked @ answer , saw list[any]
. proceeded code out implementation follows:
def flatten(lst: list[any]): list[any] = lst match { case nil => nil case x::xs => (if (x.isinstanceof[list[any]]) { flatten(x) } else { list(x) }) ::: flatten(xs) }
however, gives me following compile error:
[error] <filename omitted>:<line number omitted>: type mismatch; [error] found : [error] required: list[any] [error] (if (x.isinstanceof[any]) { flatten(x) } else {list(x) }) [error] ^ [error] 1 error found
changing isinstanceof[list[any]]
isinstanceof[list[_]]
gives same compilation error.
after short google search , consulting this solution, implemented this:
def flatten(lst: list[any]): list[any] = lst match { case nil => nil case x::xs => x match { case x: list[_] => flatten(x) ::: flatten(xs) case _ => x :: flatten(xs) } }
which works fine. why scala compiler think x
has type any
when, in order inside block, has pass x.isinstanceof[any]
, makes of type list[any]
? compiler bug, or part of scala don't understand?
thank you!
in code, x
head of list[any]
: it's any
, hence error message you're getting. need cast list[any]
, pattern matching lets quite elegantly:
def flatten(lst: list[any]): list[any] = lst match { case nil => nil case (x:list[any])::xs => flatten(x) ::: flatten(xs) case x::xs => list(x) ::: flatten(xs) }
Comments
Post a Comment