title: (Scala) Lists that can contain lists as elements
body: <p>I have been coding for two years now. I can't say I'm an expert.</p>
  
  <p>I have taken a course in functional programming in which we used Common Lisp. I heard a lot of great things about Scala, as a "<em>new</em>" language and wanted to learn it. I read a book for the basics and wanted to rewrite all the code we did in Lisp into Scala. Almost all the code was going through lists and this is where I found a problem. Most of the problems I could solve with recursively going through the list where I set it as <code>List[Any]</code>  - for example:  </p>
  
  <pre><code>def reverse(thelist: List[Any]):List[Any].....
  </code></pre>
  
  <p>but as I've found out there isn't a specific way for checking whether the head of the list is a list itself except for <code>.isInstanceOf[List[Any]]</code>  </p>
  
  <p>This was OK at first, but now I have a problem. <code>Any</code> isn't very specific, especially with comparing elements. If I wanted to have an equivalent list with, let's say, only <code>Int</code>, I can create a <code>List[Int]</code> which can only take an <code>Int</code> value as an element, none of which can be List[Int] itself. The other way, writing <code>List[List[Int]]</code> has the same problem, but in reverse, because every element has to be a <code>List</code>. </p>
  
  <p>As a solution I've tried setting the original list as <code>List[Either[Int,List[Int]]]</code>, but that only created more problems, as now I have to constantly write <code>.isInstanceOf</code> and <code>.asInstanceOf</code> in all of my ifs and recursive calls, which is time-consuming and makes the code harder to understand. But even <code>List[Either[Int,List[Int]]]</code> is a temporary solution, because it only goes one level deep. A list can contain a list that can contain a list... and so on. </p>
  
  <p>Does Scala offer a more elegant solution I am not yet aware of, such as using classes or objects in some way, or a simple elegant solution, or am I stuck with writing this kind of code? To make my question more specific, is there a way in Scala to define a list that can, but doesn't have to contain a list of the same kind as an element?</p>