【问题标题】:Scala trait - implement inside Main objectScala trait - 在 Main 对象中实现
【发布时间】:2018-04-29 11:05:49
【问题描述】:

我有一个特征并试图在Main 对象中实现它。这可能吗?最佳做法是什么?

trait PrintThis {
  def nowPrint (thing:String)
}

object Main extends PrintThis {
  def main(args: Array[String]): Unit = {

    def nowPrint(thing:String): Unit = {
      println("subject" )
    }

    nowPrint("test")

  }
}


如果这不可能 - 这是更好的方法吗(extend 另一个类中的 trait 并在另一个类中实现 trait 方法,然后 extend Main 类中的那个类并调用该方法)?

trait One {
  def show()
}

class Two extends One {
  def show() {println ("This is a show!") }
}

object Main extends Two {
  def main(args: Array[String]): Unit = {
    show()
  }
}

或者在 Main 中实例化新类而不是 extending 可能更好?

object Main  {
  def main(args: Array[String]): Unit = {
    var pointer:Two = new Two
    pointer.show()
  }
}

【问题讨论】:

    标签: scala methods interface


    【解决方案1】:

    不,这不是一个好方法。主要功能旨在开始运行您的应用程序。为什么需要从 Main 扩展任何类?如果您想使用其他类,只需调用它们的对象即可。

    【讨论】:

    • 谢谢。您介意在这样的简单示例中分享(代码)good 方法吗?
    • 用另一种有效的方法调整了问题。请发表评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多