0

How to properly extend and implement method sendEmail from Person trait (interface) inside Employee object bellow in order for main to execute:

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)
    }

  }
}
1
  • You need to implement all the abstract members of trait in the extending class Commented Apr 29, 2018 at 3:28

2 Answers 2

4

You'll need to implement all members and methods declared in trait Person. Also, assuming you have multiple employees, class (or case class) might be more suitable than 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
Sign up to request clarification or add additional context in comments.

2 Comments

What is the purpose of this line ListEmployees.main(Array())? (it works without it)
It isn't part of the code, but a command for test running ListEmployees.main() on Scala REPL.
0

The method needs to be a member of the object rather than a function inside another function (main). Try:

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")
  }
}

2 Comments

That is a good catch but still did not work: Error:(10, 8) object creation impossible, since: it has 2 unimplemented members. /** As seen from object Employee, the missing signatures are as follows. * For convenience, these are usable as stub implementations. */ def gender_=(x$1: Char): Unit = ??? def name_=(x$1: String): Unit = ??? object Employee extends Person {
You also need to implement name and gender, something like var name = "Joe" and something similar for gender should suffice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.