Scala Traits - 如何实现方法

时间:2018-04-29 02:44:40

标签: scala interface traits

如何在sendEmail对象内Person trait(接口)正确扩展和实现方法Employee,以便执行main:

trait Person {
  var name:String
  var gender:Char
  def sendEmail(subject:String, body:String)

}

object Employee extends Person {
  def main(args: Array[String]): Unit = {
    println("Hello")
    sendEmail("a", "b")

    def sendEmail(subject:String, body:String): Unit = {
      println("subject" + body)
    }

  }
}

2 个答案:

答案 0 :(得分:3)

您需要实现在特征Person中声明的所有成员和方法。此外,假设您有多名员工,class(或case class)可能比object更合适:

trait Person {
  val name: String
  val gender: Char
  def sendEmail(subject: String, body: String): Unit
}

class Employee(val name: String, val gender: Char) extends Person {
  def sendEmail(subject: String, body: String): Unit =
    println(s"subject: $subject\n   body: $body")
}

object ListEmployees {
  def main(args: Array[String]) {
    val emp1 = new Employee("Dave", 'M')
    val emp2 = new Employee("Jenn", 'F')

    emp1.sendEmail("yo", "yo yo yo")
    emp2.sendEmail("boo", "boo boo boo")
  }
}

ListEmployees.main(Array())
// subject: yo
//    body: yo yo yo
// subject: boo
//    body: boo boo boo

答案 1 :(得分:0)

该方法需要是对象的成员而不是另一个函数(main)中的函数。尝试:

object Employee extends Person {

  def sendEmail(subject:String, body:String): Unit = {
    println("subject" + body)
  }
  def main(args: Array[String]): Unit = {
    println("Hello")
    sendEmail("a", "b")
  }
}