简体   繁体   中英

Can singleton object extend a trait?

I want to extend a trait from Scala object and override those methods which are in trait. So my doubt is those methods will become static to that Object or instance methods, and is this good approach to extend from trait to Scala Object. Please help on this

trait A{
  def show:Unit
}

object B extends A{
  override def show(): Unit = { 
    println("inside Object")    
  }    
}

There are no static methods in Scala . object can indeed extend a trait . Overriden methods, like show , do not become static methods, instead they belong to a single instance of B.type . This is the singleton pattern provided by Scala's object definition facility.

Try the following in Scala REPL:

object B
B

It should output something like

res0: B.type = B$@5688722f

Note how the value B has type B.type , so B is just a value/instance, nothing to do with statics.

Hm, I think a common example/usecase of what you've just described is extending the App trait and overriding the main definition.

object test extends App
{  
  override def main (args: Array[String]): Unit = {
    println("Hello, let's get started")
  }
}

In general though, why don't you define the class itself to extend the trait?

If you are going to instantiate new instances of B using B() (instead of new B() ) it makes sense to do this.

trait A{
  def show:Unit
}

object B { // companion aka singleton object
  def apply(){
    ...
  }
}

class B extends A{
  override def show(): Unit = { 
    println("inside Object")    
  }    
}

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