I am trying to understand why Scala runtime does not complain while i try to cast one subclass into another. And how do i make scala to complain.
I have following inheritance in my application
trait I {
val i: String
}
trait K extends I {
val k: String
}
case class S(override val i:String, override val k: String, val s: String) extends K
case class M(override val i: String, val m: String) extends I
As per my understanding following method call should have thrown a class cast exception. But it works perfectly fine. listM holds list of S. And i am able to create instance of MakeM such that its member contains List of S instead of List of M. This is very confusing. How does this work? Is scala being smart in converting one subclass into another subclass. How do i enforce scala to complain when sub classes are being casted into one another.
case class MakeM(val data:String, val list: Seq[M])
object Test {
def main(args: Array[String]): Unit = {
val listOfS = Some(List(S("i1", "k1", "s1"), S("i2", "k2", "s2")))
val listOfM:Seq[M] = listOfS.get.asInstanceOf[Seq[M]] //this works , why?
val m1 = MakeM("some data", listOfM); //this works. why?
//val m2 = MakeM("some data", listOfS.get); //this fails
println(s"$m1");
}
}
Actual Output
MakeM(some data,List(S(i1,k1,s1), S(i2,k2,s2)))
Expected Output
Class Cast exception.