Type-parametrized type hierarchies - scala

I was wondering if anyone has any experience with creating a type-parametrized type hierarchy? I am fairly certain this is acheivable as a result of scala's pseudo-unification of packages & static objects.
The specific use case I have in mind is parametrizing an id type over an application framework so you can use your choice of int/long/java.util.UUID/BSONId/whatever. Consider as a rough example:
package foolib.generic
trait GenEntity[I] { def id: I }
trait GenRepository[I] { def getById(id: I): GenEntity[I] }
trait FooTaxonomy[I] {
type Entity = GenEntity[I]
type Repository = GenRepository[I]
object subpackage extends generic.subpackage.SubpackageTaxonomy[I]
}
You would then configure the hierarchy for use in a project with something like:
package object myprj {
object foolib extends foolib.generic.FooTaxonomy[java.util.UUID]
// Whee!
val someEntity = new myprj.foolib.Entity(java.util.UUID.randomUUID())
}
Are there any reasons this is a spectacularly bad idea? Any pitfalls/etc I should be aware of?

This approach would work but you may encounter problems when the number of type parameters increases. Perhaps a solution would be to use abstract type members instead of type parameters.
Another approach is to use the cake pattern which I think provides a better solution in your case. The exact logic of your code eludes me a bit, so this rewrite may not entirely represent your intention:
package foolib.generic
//defines common types used by all modules
trait CoreModule {
type Id // abstract type, not commited to any particular implementation
}
//module defining the EntityModule trait
trait EntityModule { this: CoreModule => //specifying core module as a dependency
trait GenEntity {
def id: Id
}
def mkEntity(id: Id): Entity //abstract way of creating an entity
}
//defines the GenRepository trait
trait RepositoryModule { this: EntityModule with CoreModule => //multiple dependencies
trait GenRepository {
def getById(id: Id): GenEntity
}
val repository: GenRepository //abstract way of obtaining a repository
}
//concrete implementation for entity
trait EntityImplModule extends EntityModule { this: CoreModule =>
case class Entity(val id: Id) extends GenEntity
def mkEntity(id: Id) = Entity(id)
}
//modules that provides a concrete implementation for GenRepository
trait RepositoryImplModule extends RepositoryModule { this: CoreModule with EntityModule =>
object RepositoryImpl extends GenRepository {
def getById(id: Id) = mkEntity(id)
}
}
//this unifies all your modules. You can also bind any dependencies and specify any types
object Universe
extends CoreModule
with EntityImplModule
with RepositoryImplModule {
type Id = java.util.UUID
val repository = RepositoryImpl
def mkEntity(id: Id) = Entity(id)
}
//usage
object Main {
import Universe._
import java.util.UUID
val entity = repository.getById(UUID.randomUUID())
println(entity.id)
}
This achieves your goal of creating an implementation independent of the concrete type Id and it also provides a nice way to do dependency injection.
The modules which provide a concrete implementation for GenRepository, for instance, may require a concrete type for Id. You can very well create another module which binds Id to a concrete type and make the RepositoryImplModule depend on the former module, thus specifying that this concrete implementation of GenRepository will work only for a certain type of ids.
The Cake pattern is very powerful and has many variations. This video explains it quite well, I recommend you watch it if you are interested in this solution:
Cake Pattern: The Bakery from the Black Lagoon

Related

Scala typeclass pattern and covariance

We've got several types of resources and we wanted to make a method to check if a resource is healthy or not. Given that the type of resources are very heterogeneous we didn't want to use standard subclassing and we decided to use a typeclass:
trait CanHealthCheck[T] {
def isHealthy(t: T): Boolean
}
We also have a utility method to be able to check if a given resource is alive/healthy or not
object LivenessChecker {
def isAlive[T](t: T)(implicit canHealthCheck: CanHealthCheck[T]): Boolean = {
canHealthCheck.isHealthy(t)
}
}
We've got a repository layer to access to the data. We would like to express the idea that a given abstract repository must be "health checkable" but to leave the implementation details to the subclasses implementing the trait:
trait UserRepository {
def findSomeUser(): User = ???
implicit def isHealthCheckable: CanHealthCheck[UserRepository]
}
The problem arises when we want to subclass UserRepository with a particular implementation, given that CanHealthCheck is not covariant on the type T.
class DbUserRepository extends UserRepository {
def ping: Boolean = ???
override implicit val isHealthCheckable: CanHealthCheck[UserRepository] =
new CanHealthCheck[DbUserRepository] {
def isHealthy(db: DbUserRepository) = db.ping
}
}
And this is an example of some dummy function that acts on the abstract repository while trying to check if the repository is alive:
def someDummyFunction(userRepository: UserRepository) = {
if(LivenessChecker.isAlive(userRepository)) // This won't compile
userRepository.findSomeUser()
}
The idea is that our application uses the UserRepository trait and not the implementation, and thus we cannot check whether the repository is alive or not. How can we continue using the repository abstraction layer and be able to check if a given (abstract) repository is alive? Is the typeclass pattern the correct pattern to use here?
There is something a bit fishy with isHealthCheckable inside UserRespository. The isHealthy method, when called, would have two instances of UserRepository available: of course, the one passed as the t argument, but also, the UserRepository.this of the enclosing instance.
This is a sign of something wrong. Either the method should be written somewhere else, so that it does not get enclosing this, or it should not get the argument
That second option is consistent with using UserRepository the object-oriented, subtyping way. Also, it is consistent with your idea that every UserRepository must be heath-checkable. Just do
trait UserRepository {
...
def isHealty: Boolean
}
It is fine to call that directly, userDirectory.isHealthy. But you can then also easily implement the type class:
object UserRepository {
implicit val canHealthCheck = new CanHealthCheck[UserRepository] {
def isHealthy(repository: UserRepository) = repository.IsHealthy
}
}
also note that it was not clear at all how the implicit instance method would have come into the implicit scope. With the companion object, it works fine.
Use "type bounds".
I couldn't test this, but to get the code to compile, you could do something like:
class DbUserRepository[U <: UserRepository] extends UserRepository {
def ping: Boolean = ???
implicit val isHealthCheckable: CanHealthCheck[U] =
new CanHealthCheck[U] {
def isHealthy(db: U) = db.ping
}
}

Inheriting self-typed trait with another trait in Scala

I'm trying to design a small module system for my application such that I can do this:
new MyApplication extends Module1 with Module2 ... with ModuleN
In order to let my modules register themselves with the application, I also have:
trait ModuleRegistry {
def register(start: () => Unit) = // Stores start functions in a list
}
trait Module {
self: ModuleRegistry =>
self.register(start)
def start(): Unit
}
class Application extends ModuleRegistry {
}
trait Module1 extends Module {
...
}
The idea is that modules can register a function with the registry to be called when the application starts up. Unfortunately, the Scala compiler forces me to do this:
trait Module1 extends Module {
self: ModuleRegistry =>
}
meaning that all implementations of a module have to explicitly self-type themselves with the registry, when ideally they'd have no knowledge of it.
So my questions are:
Why does the compiler force me to re-specify this self-type on an extending trait? Ideally I don't even want the extending trait to 'see' this type, as it should be handled by the base Module trait. The 'concrete' module is meant to be implemented by 3rd parties, so exposing the registry to them seems kinda ugly.
Is there a better way to do what I'm trying to achieve in Scala so that modules can be freely mixed in?
This isn't a good use of the cake pattern, as you want all the modules to retain their own functionality (presumably), not mix and overwrite each other when mixed in. If you want the latter, you shouldn't: only with very careful design can this give predictable and sane results, and if third parties are supposed to provide the modules it's pretty much guaranteed that the design will not be that careful.
Instead, you should adhere to the "favor composition over inheritance" advice.
trait Module {
def start: Unit
}
trait Modular {
protected def moduleList: Seq[Module]
protected def register() = moduleList.map(m => m.start _)
}
class Application(modules: Module*) extends Modular {
protected def moduleList: Seq[Module] = modules // Fix varargs type
protected val registered = register()
}
object Module1 extends Module {
def start = println("One")
}
object Module2 extends Module {
def start = println("Two")
}
val app = new Application(Module1, Module2) {
registered.foreach(_())
}
// Prints "One", then "Two"
This is assuming a singleton is okay for a module. If you need a specific instance, you can either override apply (syntax is then Module1()) in the companion object, or add a builder trait that Module1 extends (e.g. trait ModuleBuilder { def module: Module }).

Reify name of class implementing trait as String, from the trait itself

I have a trait that's implemented by a large number of classes, and I'd like to use the names of the classes that implement this trait at runtime, but with as much code centralized as possible.
Specifically, in my code, I'm using tokens to represent classes to be initialized at runtime. The tokens carry configuration, and the actual class is instantiated as needed via the token, combined with run-time information. For linking with resources outside of my app, I want to be able to access the name of the class for which a token is defined. See the example:
trait Token[Cls] {
val className = ???
// Example generic method depending on final class name
def printClassName = println(className)
}
case class ClassA(t: ClassAToken, runtimeContext: String) {
// a bunch of other code
}
object ClassA {
case class ClassAToken(configParam: String) extends Token[ClassA]
}
So, I'm trying to implement className. Ideally, I can pull this information once at compile time. How can I do this, while keeping boilerplate code out of ClassA? Although, if I can drop the type parameter and get the name of the class implementing the Token trait at runtime, that's great too.
Due to Type Erasure Cls is not available on runtime anymore. To get the informations at runtime, you need to use a TypeTag (in your case a ClassTag).
Your code could look like this:
import scala.reflect._
trait Token[Cls] {
def className(implicit ct: ClassTag[Cls]) = ct.runtimeClass.getName
// Example generic method depending on final class name
def printClassName(implicit ct: ClassTag[Cls]) = println(className)
}
case class ClassA(t: ClassAToken, runtimeContext: String) {
// a bunch of other code
}
object ClassA {
case class ClassAToken(configParam: String) extends Token[ClassA]
}
or if it is possible for you to let Token be an class, you could use the ClassTag context bounds:
import scala.reflect._
class Token[Cls: ClassTag] {
def className = classTag[Cls].runtimeClass.getName
// Example generic method depending on final class name
def printClassName = println(className)
}
case class ClassA(t: ClassAToken, runtimeContext: String) {
// a bunch of other code
}
object ClassA {
case class ClassAToken(configParam: String) extends Token[ClassA]
}
For more informations on TypeTags/ClassTags see Scala: What is a TypeTag and how do I use it?

How to design immutable model classes when using inheritance

I'm having trouble finding an elegant way of designing a some simple classes to represent HTTP messages in Scala.
Say I have something like this:
abstract class HttpMessage(headers: List[String]) {
def addHeader(header: String) = ???
}
class HttpRequest(path: String, headers: List[String])
extends HttpMessage(headers)
new HttpRequest("/", List("foo")).addHeader("bar")
How can I make the addHeader method return a copy of itself with the new header added? (and keep the current value of path as well)
Thanks,
Rob.
It is annoying but the solution to implement your required pattern is not trivial.
The first point to notice is that if you want to preserve your subclass type, you need to add a type parameter. Without this, you are not able to specify an unknown return type in HttpMessage
abstract class HttpMessage(headers: List[String]) {
type X <: HttpMessage
def addHeader(header: String):X
}
Then you can implement the method in your concrete subclasses where you will have to specify the value of X:
class HttpRequest(path: String, headers: List[String])
extends HttpMessage(headers){
type X = HttpRequest
def addHeader(header: String):HttpRequest = new HttpRequest(path, headers :+header)
}
A better, more scalable solution is to use implicit for the purpose.
trait HeaderAdder[T<:HttpMessage]{
def addHeader(httpMessage:T, header:String):T
}
and now you can define your method on the HttpMessage class like the following:
abstract class HttpMessage(headers: List[String]) {
type X <: HttpMessage
def addHeader(header: String)(implicit headerAdder:HeaderAdder[X]):X = headerAdder.add(this,header) }
}
This latest approach is based on the typeclass concept and scales much better than inheritance. The idea is that you are not forced to have a valid HeaderAdder[T] for every T in your hierarchy, and if you try to call the method on a class for which no implicit is available in scope, you will get a compile time error.
This is great, because it prevents you to have to implement addHeader = sys.error("This is not supported")
for certain classes in the hierarchy when it becomes "dirty" or to refactor it to avoid it becomes "dirty".
The best way to manage implicit is to put them in a trait like the following:
trait HeaderAdders {
implicit val httpRequestHeaderAdder:HeaderAdder[HttpRequest] = new HeaderAdder[HttpRequest] { ... }
implicit val httpRequestHeaderAdder:HeaderAdder[HttpWhat] = new HeaderAdder[HttpWhat] { ... }
}
and then you provide also an object, in case user can't mix it (for example if you have frameworks that investigate through reflection properties of the object, you don't want extra properties to be added to your current instance) (http://www.artima.com/scalazine/articles/selfless_trait_pattern.html)
object HeaderAdders extends HeaderAdders
So for example you can write things such as
// mixing example
class MyTest extends HeaderAdders // who cares about having two extra value in the object
// import example
import HeaderAdders._
class MyDomainClass // implicits are in scope, but not mixed inside MyDomainClass, so reflection from Hiberante will still work correctly
By the way, this design problem is the same of Scala collections, with the only difference that your HttpMessage is TraversableLike. Have a look to this question Calling map on a parallel collection via a reference to an ancestor type

Why use scala's cake pattern rather than abstract fields?

I have been reading about doing Dependency Injection in scala via the cake pattern. I think I understand it but I must have missed something because I still can't see the point in it! Why is it preferable to declare dependencies via self types rather than just abstract fields?
Given the example in Programming Scala TwitterClientComponent declares dependencies like this using the cake pattern:
//other trait declarations elided for clarity
...
trait TwitterClientComponent {
self: TwitterClientUIComponent with
TwitterLocalCacheComponent with
TwitterServiceComponent =>
val client: TwitterClient
class TwitterClient(val user: TwitterUserProfile) extends Tweeter {
def tweet(msg: String) = {
val twt = new Tweet(user, msg, new Date)
if (service.sendTweet(twt)) {
localCache.saveTweet(twt)
ui.showTweet(twt)
}
}
}
}
How is this better than declaring dependencies as abstract fields as below?
trait TwitterClient(val user: TwitterUserProfile) extends Tweeter {
//abstract fields instead of cake pattern self types
val service: TwitterService
val localCache: TwitterLocalCache
val ui: TwitterClientUI
def tweet(msg: String) = {
val twt = new Tweet(user, msg, new Date)
if (service.sendTweet(twt)) {
localCache.saveTweet(twt)
ui.showTweet(twt)
}
}
}
Looking at instantiation time, which is when DI actually happens (as I understand it), I am struggling to see the advantages of cake, especially when you consider the extra keyboard typing you need to do for the cake declarations (enclosing trait)
//Please note, I have stripped out some implementation details from the
//referenced example to clarify the injection of implemented dependencies
//Cake dependencies injected:
trait TextClient
extends TwitterClientComponent
with TwitterClientUIComponent
with TwitterLocalCacheComponent
with TwitterServiceComponent {
// Dependency from TwitterClientComponent:
val client = new TwitterClient
// Dependency from TwitterClientUIComponent:
val ui = new TwitterClientUI
// Dependency from TwitterLocalCacheComponent:
val localCache = new TwitterLocalCache
// Dependency from TwitterServiceComponent
val service = new TwitterService
}
Now again with abstract fields, more or less the same!:
trait TextClient {
//first of all no need to mixin the components
// Dependency on TwitterClient:
val client = new TwitterClient
// Dependency on TwitterClientUI:
val ui = new TwitterClientUI
// Dependency on TwitterLocalCache:
val localCache = new TwitterLocalCache
// Dependency on TwitterService
val service = new TwitterService
}
I'm sure I must be missing something about cake's superiority! However, at the moment I can't see what it offers over declaring dependencies in any other way (constructor, abstract fields).
Traits with self-type annotation is far more composable than old-fasioned beans with field injection, which you probably had in mind in your second snippet.
Let's look how you will instansiate this trait:
val productionTwitter = new TwitterClientComponent with TwitterUI with FSTwitterCache with TwitterConnection
If you need to test this trait you probably write:
val testTwitter = new TwitterClientComponent with TwitterUI with FSTwitterCache with MockConnection
Hmm, a little DRY violation. Let's improve.
trait TwitterSetup extends TwitterClientComponent with TwitterUI with FSTwitterCache
val productionTwitter = new TwitterSetup with TwitterConnection
val testTwitter = new TwitterSetup with MockConnection
Furthermore if you have a dependency between services in your component (say UI depends on TwitterService) they will be resolved automatically by the compiler.
Think about what happens if TwitterService uses TwitterLocalCache. It would be a lot easier if TwitterService self-typed to TwitterLocalCache because TwitterService has no access to the val localCache you've declared. The Cake pattern (and self-typing) allows for us to inject in a much more universal and flexible manner (among other things, of course).
I was unsure how the actual wiring would work, so I've adapted the simple example in the blog entry you linked to using abstract properties like you suggested.
// =======================
// service interfaces
trait OnOffDevice {
def on: Unit
def off: Unit
}
trait SensorDevice {
def isCoffeePresent: Boolean
}
// =======================
// service implementations
class Heater extends OnOffDevice {
def on = println("heater.on")
def off = println("heater.off")
}
class PotSensor extends SensorDevice {
def isCoffeePresent = true
}
// =======================
// service declaring two dependencies that it wants injected
// via abstract fields
abstract class Warmer() {
val sensor: SensorDevice
val onOff: OnOffDevice
def trigger = {
if (sensor.isCoffeePresent) onOff.on
else onOff.off
}
}
trait PotSensorMixin {
val sensor = new PotSensor
}
trait HeaterMixin {
val onOff = new Heater
}
val warmer = new Warmer with PotSensorMixin with HeaterMixin
warmer.trigger
in this simple case it does work (so the technique you suggest is indeed usable).
However, the same blog shows at least other three methods to achieve the same result; I think the choice is mostly about readability and personal preference. In the case of the technique you suggest IMHO the Warmer class communicates poorly its intent to have dependencies injected. Also to wire up the dependencies, I had to create two more traits (PotSensorMixin and HeaterMixin), but maybe you had a better way in mind to do it.
In this example I think there is no big difference. Self-types can potentially bring more clarity in cases when a trait declares several abstract values, like
trait ThreadPool {
val minThreads: Int
val maxThreads: Int
}
Then instead of depending on several abstract values you just declare dependency on a ThreadPool.
Self-types (as used in Cake pattern) for me are just a way to declare several abstract members at once, giving those a convenient name.