简体   繁体   English

singleton对象可以扩展一个特征吗?

[英]Can singleton object extend a trait?

I want to extend a trait from Scala object and override those methods which are in trait. 我想从Scala对象扩展一个特征并覆盖那些特征中的方法。 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. 所以我怀疑这些方法将成为对象或实例方法的静态方法,并且这是从trait扩展到Scala对象的好方法。 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 . Scala中没有静态方法 object can indeed extend a trait . object确实可以扩展一个trait Overriden methods, like show , do not become static methods, instead they belong to a single instance of B.type . show这样的Overriden方法不会成为静态方法,而是属于B.type单个实例 This is the singleton pattern provided by Scala's object definition facility. 这是Scala的object定义工具提供的单例模式。

Try the following in Scala REPL: 在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. 注意 B类型是B.type ,所以B只是一个值/实例,与静态无关。

Hm, I think a common example/usecase of what you've just described is extending the App trait and overriding the main definition. 嗯,我认为你刚刚描述的一个常见的例子/用例是扩展App特性并覆盖main定义。

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. 如果要使用B() (而不是new B() )实例化B新实例,则执行此操作是有意义的。

trait A{
  def show:Unit
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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