假设我有两个类Person
和Business
,它们由 trait 扩展Entity
。
trait Entity
case class Person(name: String) extends Entity
case class Business(id: String) extends Entity
假设我不能更改Entity
,Person
并且Business
(它们在不同的文件中并且不被更改)我如何定义一个函数,比如 a printEntity
,它打印字段name
或id
,取决于实体?例如,给定 and 的实例,Person
我Business
该如何做这样的事情:
object Main extends App {
val person1: Person = Person("Aaaa Bbbb")
val business1: Business = Business("0001")
// How can I do something like this?
person1.printEntity // would call a function that executes println(id)
business1.printEntity // would call a function that executes println(name)
}
任何想法表示赞赏!对不起,缺乏背景,我还在学习!