Reputation: 161
I create one abstract class and two real class
abstract class ProcElems {
def invoke()
}
class Brick(title: String) extends ProcElems {
def invoke {
println("invoked brick")
}
}
class Block(title:String) extends ProcElems {
def block_method = println("1")
override def invoke {
println("invoked block")
}
}
Now i defining a List with Abstract class type and add to it some object like brick and block types
val l: List[ProcElems] = List(Title: block, Title: brick, Title: block)
and when i try invoke block_method on first element it gives me error, because ProcElems doesnt have that method. But when i do
l.head.getClass #/ gives the real(non abstract) class Block
Question: How i can call block_method on list element with abstract class type?
Upvotes: 1
Views: 1175
Reputation: 1041
Similar to wheaties' answer, you can use collect
with a PartialFunction
to get a collection containing only those elements where the partial function applies:
scala> val l: List[ProcElems] = List(new Brick("brick"), new Block("block1"), new Block("block2"))
scala> val blocks = l.collect { case block: Block => block }
blocks: List[Block] = List(Block@d14a362, Block@45f27da3)
You now have a List[Block]
that you can use as you see fit:
scala> blocks.head.block_method
1
scala> blocks.foreach(_.block_method)
1
1
Upvotes: 2
Reputation: 35990
You a PartialFunction
aproach:
myList.foreach{
case x:Block => x.block_method
case _ =>
}
Upvotes: 2