简体   繁体   中英

Scala List with abstract class type and accessing to child

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?

You a PartialFunction aproach:

myList.foreach{
  case x:Block => x.block_method
  case _ =>
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM