[英]Scala Traits - how to implement method
How to properly extend and implement method sendEmail
from Person
trait (interface) inside Employee
object bellow in order for main to execute: 如何从Employee
对象下面的Person
特性(接口)正确扩展和实现方法sendEmail
以使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)
}
}
}
You'll need to implement all members and methods declared in trait Person
. 您需要实现在trait Person
声明的所有成员和方法。 Also, assuming you have multiple employees, class
(or case class
) might be more suitable than object
: 另外,假设您有多个雇员,则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
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")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.