I created an abstract base class as follows:
abstract class parent
Then I went ahead and created two case classes inheriting from the parent class:
case class child1(name:String,category:String) extends parent
case class child2(name:String,category1:String,category2:String) extends parent
Then for kicks I created a list of type parent and appended child1 and child2 to it:
val childList = List[parent]()
scala> child1("Child","One") :: child2("Child","Two","dhshs")::childList
res2: List[parent] = List(child1(Child,One), child2(Child,Two,dhshs))
So far so good, the List[Parent] has the two child types in it.
Now, I want to traverse the List and based on the underlying type of the child, do something special for that particular type. So I do this:
scala> res2 map {case child1 => "Child1";case child2 => "Child2"}
I expected to see a List[String]("Child1","Child2"), instead I got the following:
<console>:15: error: unreachable code
res2 map {case child1 => "Child1";case child2 => "Child2"}
Now for some more kicks, I did the following:
scala> res2 map {r => r match {case child1 => "Child1"}}
res8: List[java.lang.String] = List(Child1, Child1)
scala> res2 map {case child1 => "Child1"}
res9: List[java.lang.String] = List(Child1, Child1)
As you can see, I got “Child1” as my List entry, even for “child2” I get a Child1.
Pretty confused, can somebody tell me whats going on here?
The problem is here: child1 and child2 are new variables created to house the result.
try this:
xandyare the variables with the associated typeschild1andchild2respectively.