1 package chapter06
2
3 object Test16_TraitSelfType {
4 def main(args: Array[String]): Unit = {
5 val user = new RegisterUser("alice", "123456")
6 user.insert()
7 }
8 }
9
10 // 用户类
11 class User(val name: String, val password: String)
12
13 trait UserDao {
14 _: User =>
15
16 // 向数据库插入数据
17 def insert(): Unit = {
18 println(s"insert into db: ${this.name}")
19 }
20 }
21
22 // 定义注册用户类
23 class RegisterUser(name: String, password: String) extends User(name, password) with UserDao
想要在UserDao特质中使用User的账号和密码属性,又不想有继承的关系,那么可以使用类似依赖注入的方式,使用_:User => 注入一个User的对象,这样就可以使用User的属性了