简体   繁体   中英

Scala: Force child class to override all parent methods

Is there any way to force the child classes to override all methods in the parent class in Scala? In Python there is @abstractmethod decorator to do the same, this would throw an exception if child class does not override the method. In looking for if such feature is available in scala..

Yes. Make your parent class abstract , and don't implement any methods that you want the derived classes to be forced to implement.

abstract class Foo {
  def foo(s: String): Int
}

Here's what would happen (at compile time) if a child class failed to implement foo

scala> class Bar extends Foo
<console>:12: error: class Bar needs to be abstract, since method foo in 
class Foo of type (s: String)Int is not defined
   class Bar extends Foo
         ^

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