I am trying to learn about a pie template.
I read this blog about it.
Sample code from this blog:
case class User (name:String,email:String,supervisorId:Int,firstName:String,lastName:String) trait UserRepository { def get(id: Int): User def find(username: String): User } trait UserRepositoryComponent { def userRepository: UserRepository trait UserRepository { def get(id: Int): User def find(username: String): User } } trait Users { this: UserRepositoryComponent => def getUser(id: Int): User = { userRepository.get(id) } def findUser(username: String): User = { userRepository.find(username) } } trait UserInfo extends Users { this: UserRepositoryComponent => def userEmail(id: Int): String = { getUser(id).email } def userInfo(username: String): Map[String, String] = { val user = findUser(username) val boss = getUser(user.supervisorId) Map( "fullName" -> s"${user.firstName} ${user.lastName}", "email" -> s"${user.email}", "boss" -> s"${boss.firstName} ${boss.lastName}" ) } } trait UserRepositoryComponentImpl extends UserRepositoryComponent { def userRepository = new UserRepositoryImpl class UserRepositoryImpl extends UserRepository { def get(id: Int) = { ??? } def find(username: String) = { ??? } } } object UserInfoImpl extends UserInfo with UserRepositoryComponentImpl
I can simplify this code by removing Users :
package simple { case class User(name: String, email: String, supervisorId: Int, firstName: String, lastName: String) trait UserRepository { def get(id: Int): User def find(username: String): User } trait UserRepositoryComponent { def userRepository: UserRepository trait UserRepository { def get(id: Int): User def find(username: String): User } } trait UserInfo { this: UserRepositoryComponent => def userEmail(id: Int): String = { userRepository.get(id).email } def userInfo(username: String): Map[String, String] = { val user = userRepository.find(username) val boss = userRepository.get(user.supervisorId) Map( "fullName" -> s"${user.firstName} ${user.lastName}", "email" -> s"${user.email}", "boss" -> s"${boss.firstName} ${boss.lastName}" ) } } trait UserRepositoryComponentImpl extends UserRepositoryComponent { def userRepository = new UserRepositoryImpl class UserRepositoryImpl extends UserRepository { def get(id: Int) = { ??? } def find(username: String) = { ??? } } } object UserInfoImpl extends UserInfo with UserRepositoryComponentImpl }
and it just compiles.
1) Why is the blog code so complicated?
2) Is this an idiomatic way to use a cake template?
3) Why is the Users class needed in this example?
4) This is what the cake template should look like (with this seemingly unnecessary Users class?
5) Or just a simplified version?
source share