Scala traits with generic - scala

I used to develop on java, but now I stucked with one thing.
I have some kind of flexible value system.
trait Value[T] {
def get:T
}
I have implementations of this, for example
class StringValue(value : String) extends Value[String] {
override def get : String = value
}
class NumberValue(value : Int) extends Value[Int] {
override def get: Int = value
}
Then, I'm passing Value to Map, but I don't need parameter, as I don't know which implementation should be used.
case class Foo(attributes: Map[Attribute, Value)
On this step I get an error, because Value should have parameter.
I understand that it's might be fundamental difference between Java and Scala, so what should I use in this case?

You can use existential types: Map[Attribute, Value[_]] to express this, but they aren't trivial to use.
I understand that it's might be fundamental difference between Java and Scala
It isn't: in Java you can write Map<Attribute, Value>, but you shouldn't. Instead, you want Map<Attribute, Value<?>> which is more limited than Scala, but expresses the same idea.

You can try something along the lines of
case class Foo[K, V](attributes: Map[K, V])
You need to have the class have generic typed parameters in order to be able to use generic parameters.

Related

Is using Any for Union type a good idea?

I want to create a class generator (for Avro models). I have a problem because sometime the field of the class I generate could be one of many different types, let's say it could be an Int or a String or whatever. The simple idea is to create that field with the type Any and check at runtime that it is ok.
The problem is that using Any discard some of the powerfull features of the scala type system. Some bug in the code will not be caught at compile time (if I give a List to a function expecting a String or Int covered by an Any).
For example :
Let's I have this description of my class :
{"className" : "MyClass", "fields" : [
{ "fieldName" : "myField", "type" : ["String", "Int"]}
]}
From this description, I create this class :
class MyClass(myField: Any)
I want to create something like this :
class MyClass(myField: String or Int)
Should I stop using Any ? Is using Any generally considered a good idea in the scala community ?
Is using Any generally considered a good idea in the scala community?
Nope. Any means no type information, so it's generally considered a bad practice.
In Scala you can express a union type using Either, although it gets cumbersome if you have a lot of possible types in the union. Example:
class MyClass(myField: Either[String, Int]) {
def doSomething = myField match {
case Left(myStringField) => ???
case Right(myIntField) => ???
}
}
Another viable approach would be to make MyClass generic in its type:
class MyClass[A](myField: A)
However this is not setting any constraint on the type of A.
In order to place a constraint, e.g. make it a finite subset of types, you can use ad-hoc polymorphism:
trait MyConstraint[A]
class MyClass[A: MyConstraint](myField: A)
Now new MyClass(myValue) won't compile unless there is an implicit MyConstraint[A] in scope. Now you can whitelist the types you want to allow using implicit values
implicit object IntConstraint extends MyConstraint[Int]
implicit object StringConstraint extends MyConstraint[String]
Example:
new MyClass(42) // ok, there's implicit evidence of MyConstraint[Int]
new MyClass("foo") // ok, there's implicit evidence of MyConstraint[String]
new MyClass(false) // won't compile, no implicit evidence of MyConstraint[Boolean]
In technical terms, MyConstraint is a type class, used to refine the type A in the constructor of MyClass.
You can characterize a type class even further, by requiring that a set of operations are defined for each of its instances. E.g.
trait MyConstraint[A] {
def mandatoryOp: A
}
implicit object IntConstraint extends MyConstraint[Int] {
def mandatoryOp = 42
}
implicit object StringConstraint extends MyConstraint[String] {
def mandatoryOp = "foo"
}
class MyClass[A](myField: A)(implicit ev: MyConstraint[A]) {
def doSomething: A = ev.mandatoryOp
}
Please note that A: MyConstraint is just syntactic sugar for requiring an implicit parameter of type MyConstraint[A]. In the last example I chose the explicit syntax in order to have the implicit parameter ev available in scope.

Scala Akka - generics type in receive handler

I am trying to get my head around on what is best way to code this implementation. To give you example, here is my DAO handler code looks like
trait IDAOHandler[+T] {
def create[U <: AnyRef: Manifest](content: U): Try[String]
}
class MongoDAOHAndler extends IDAOHandler[+T]...
So I am creating actor that will handle all my persistence task that includes serializing the content and updating MongoDB database.
So I am using akka and the trick is in receive method, how do i handle generics type parameter. Even though my actor code is non-generic, but the messages it is going to receive will be generic type and based on content type in createDAO I was planning to get appropriate DAO handler (described aboe) and invoke the method.
case class createDAO[T](content: T) (implicit val metaInfo:TypeTag[T])
class CDAOActor(daofactory: DAOFactory) extends BaseActor {
def wrappedReceive = {
case x: createDAO[_] => pmatch(x)
}
def pmatch[A](c: createDAO[A]) {
//getting dao handler which will not work because it needs manifest
}
}
Let me know if there are any other ways to re-write this implementation.
You might already know this, but a little background just to be sure: In Scala (and Java) we have what is called type erasure, this means that the parametric types are used to verify the correctness of the code during compile time but is then removed (and "does not give a runtime cost", http://docs.oracle.com/javase/tutorial/java/generics/erasure.html). Pattern matching happens during runtime so the parametric types are already erased.
The good news is that you can make the Scala compiler keep the erased type by using TypeTag like you have done in your case class or ClassTag which contains less information but also keeps the erased type. You can get the erased type from the method .erasure (.runtimeClass in Scala 2.11) which will return the Java Class of the T type. You still wont be able to use that as the type parameter for a method call as that again happens compile time and you are now looking at that type in runtime, but what you can do is to compare this type during runtime with if/else or patternmatching.
So for example you could implement a method on your daofactory that takes a Class[_] parameter and returns a DAO instance for that class. In pmatch you would then take the erased type out of the tag and pass on to it.
Here is some more info about the tags, why they exist and how they work:
http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
I took a bit different approach, kind of dispatcher pattern, so here is the revised code
trait IDAOProcess
{
def process(daofactory:IDAOFactory,sender:ActorRef)
}
case class createDAO[T <: AnyRef : Manifest](content:T) (implicit val metaInfo:TypeTag[T]) extends IDAOProcess
{
def process(daofactory:IDAOFactory,sender:ActorRef)
{
for ( handler <- daofactory.getDAO[T] )
{
handler.create(content)
}
}
}
class DAOActor(daofactory:IDAOFactory) extends BaseActor
{
def wrappedReceive =
{
case x:IDAOProcess =>
{
x.process(daofactory,sender)
}
}
}

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

Pattern matching with generics

Given the following class pattern match:
clazz match {
case MyClass => someMethod[MyClass]
}
Is it possible to refer to MyClass in a generic way based on what the pattern match came up with? For example, if I have multiple subclasses of MyClass, can I write a simple pattern match to pass the matched type to someMethod:
clazz match {
case m <: MyClass => someMethod[m]
}
Unfortunately types are not really first class citizens in Scala. This means for example that you cannot do pattern matching on types. A lot of information is lost due to stupid type erasure inherited from the Java platform.
I don't know if there are any improvement requests for this, but this is one of the worst problems in my option, so someone should really come up with such a request.
The truth is you will need to pass around evidence parameters, at best in the form of implicit parameters.
The best I can think of goes in the line of
class PayLoad
trait LowPriMaybeCarry {
implicit def no[C] = new NoCarry[C]
}
object MaybeCarry extends LowPriMaybeCarry {
implicit def canCarry[C <: PayLoad](c: C) = new Carry[C]
}
sealed trait MaybeCarry[C]
final class NoCarry[C] extends MaybeCarry[C]
final class Carry[C <: PayLoad] extends MaybeCarry[C] {
type C <: PayLoad
}
class SomeClass[C <: PayLoad]
def test[C]( implicit mc: MaybeCarry[C]) : Option[SomeClass[_]] = mc match {
case c: Carry[_] => Some(new SomeClass[ c.C ])
case _ => None
}
but still I can't get the implicits to work:
test[String]
test[PayLoad] // ouch, not doin it
test[PayLoad](new Carry[PayLoad]) // sucks
So if you want to save yourself serous brain damage, I would forget about the project or look for another language. Maybe Haskell is better here? I'm still hoping that we can eventually match types, but my hopes are pretty low.
Maybe the guys from scalaz have come up with a solution, they pretty much exploited the type system of Scala to the limits.
Your code is not really clear, because at least in java clazz is a typical name for variables of type java.lang.Class and variations. I still believe that clazz is not an instance of Class but of your own class.
In Java and Scala, given an object o: AnyRef you can get access to its class at runtime via o.getClass: Class[_], and for instance create instances of that class through the Reflection API. However, type parameters are passed at compile-time, so you can't pass a type as-is at compile time. Either you use AnyRef all over the place as type (which will work, I assume) or you use the reflection API if you have more advanced needs.

Scala: How to make requirements of the type parametres of generic classes?

I'm creating some parameterized classes C[T] and I want to make some requirements of the characteristics of the type T to be able to be a parameter of my class. It would be simple if I just wanted to say that T inherited from traits or classes (as we do with Ordering). But I want it to implement some functions as well.
For example, I've seen that many pre-defined types implement MinValue and MaxValue, I would like my type T to implement these too. I've received some advice to just define an implicit function. But I wouldn't like that all the users were obliged to implement this function for these when it is already implemented. I could implement them at my code too, but it seems just to be a poor quick fix.
For example, when defining heaps, I would like to allowd users to construct a empty Heap. In these cases I want to inicialize value with the minimum value the type T could have. Obviously this code does not works.
class Heap[T](val value:T,val heaps:List[Heap[T]]){
def this()=this(T.MinValue,List())
}
I also would love to receive some advice about really good online Scala 2.8 references.
A bunch of things, all loosely related by virtue of sharing a few methods (though with different return types). Sure sounds like ad-hoc polymorphism to me!
roll on the type class...
class HasMinMax[T] {
def maxValue: T
def minValue: T
}
implicit object IntHasMinMax extends HasMinMax[Int] {
def maxValue = Int.MaxValue
def minValue = Int.MinValue
}
implicit object DoubleHasMinMax extends HasMinMax[Double] {
def maxValue = Double.MaxValue
def minValue = Double.MinValue
}
// etc
class C[T : HasMinMax](param : T) {
val bounds = implicitly[HasMinMax[T]]
// now use bounds.minValue or bounds.minValue as required
}
UPDATE
The [T : HasMinMax] notation is a context bound, and is syntactic sugar for:
class C[T](param : T)(implicit bounds: HasMinMax[T]) {
// now use bounds.minValue or bounds.minValue as required
}
You can either use type bounds:
trait Base
class C[T <: Base]
enabling C to be parametrized with any type T which is a subtype of Base.
Or you can use implicit parameters to express requirements:
trait Requirement[T] {
def requiredFunctionExample(t: T): T
}
class C[T](implicit req: Requirement[T])
Thus, objects of class C can only be constructed if there exists an implementation of the Requirement trait for the type T you wish to parametrize them with. You can place implementations of Requirement for different types T in, for instance, a package object, thus bringing them into scope whenever the corresponding package is imported.