import scala.collection.mutable
class Session
trait SessionProvider:
def session: Session
trait DefaultSessionProvider extends SessionProvider:
val dummySession = new Session
override def session = dummySession
abstract class Identity
trait IdentityCache:
def getOrAuthenticate():Session
trait InMemoryIdentityCache extends SessionProvider:
val cache = mutable.Map.empty[Session, SessionProvider]
override def getOrAuthenticate():InMemoryIdentityCache =
cache.getOrElseUpdate(session, authenticate())
trait Authenticator:
def authenticate():Session
trait UsesSAMLIdentity:
class SAMLIdentity(val saml: String) extends Identity
trait SAMLAuthenticator extends Authenticator with UsesSAMLIdentity:
val dummySAMLIdentity = new SAMLIdentity("XXX")
override def authenticate() = dummySAMLIdentity
trait RoleManager:
def hasRole(role: String): Boolean
trait SAMLRoleManager extends RoleManager with UsesSAMLIdentity:
override def hasRole(role: String): Boolean =
val identity = getOrAuthenticate()
identity.saml == "XXX"
object WebApp extends SAMLRoleManager :
def main(args: Array[String]): Unit =
println(hasRole("YYY")) // Prints "true"
I am new in Scala and I am trying to implement the above code to print true in main. My problem is that my IDE says "Not found: authenticate" and "Not found session" in trait InMemoryIdentityCache. I am a little confused about how to implement this cake pattern.
I will appreciate any help.
InMemoryIdentityCacheextendsSessionProviderbut doesn't implementsession. So whatever extends it would have to provide it. From what I see onlyDefaultSessionProviderhas it defined, but nothing mixes it in. Actually nobody mixes-in anySessionProvideras far as I can see).InMemoryIdentityCachedoesn't extendAuthenticatorso it cannot accessauthenticate(). If you want to tell compiler that it should extendsAuthenticatorand a method will be there, you need:The fact that "final" cake might have all the methods doesn't allow you to miss them in the intermediate cake layers.
Also cake pattern is widely recognized as antipattern. Rewrite your code to use constructors to inject dependencies and you'll immediately see where there are issues and why.