Enforce a Parameter is a case class - scala

I'm trying to build a function that takes a generic case class, but I want to insure that the passed parameter is indeed a case class.
Searching has turned up only things about inheritance with self defined case classes but not about generic case classes. A guaranteed, messier, way of doing this is to use reflection to run a check on the passed case class object before do things. If it is not a case, throw an exception:
def handleCaseClass[A](caseClass:A):Unit = {
val isCaseClass = // use reflection to check
if (isCaseClass) { /*do work */ } else { throw invalidArgumentException }
}
This could get a little messy, but not a big deal. I was wondering if there was a cleaner way by using type bounds, but I've searched around and can't find anything of the like:
def handleCaseClass[A <: ???](caseClass:A):Unit = {
/* do work */
}
Is anything like this possible? Also, what would be best practices?

Related

How to restrict the types of all methods in a Scala object?

I'm trying to do something that I'm not completely sure that is either possible or makes sense.
I have an abstraction which, in order words, depends heavily on an object to tell which version of a given component is to be used. It goes like this:
object ComponentManager {
def component1Version: ComponentVersion = Component1Version1()
def component2Version: ComponentVersion = Component2Version3()
}
What I want to achieve here is to limited all methods in ComponentManager object to conform to the type ComponentVersion. I could define a trait to enforce the types, but I don't know in advance how many components will I have. Therefore, I might end up with people adding to the manager object some stuff like:
object ComponentManager {
def component1Version: ComponentVersion = Component1Version1()
def component2Version: ComponentVersion = Component2Version3()
def component3Version = objectWithWrongType() // this is the problematic line
}
For the component3Version, we have the offending object. It will compile, but I would rather have a compilation error when such a thing happens, because I have some checks that come "freely" with the proper typing.
Again, I don't know how many components will the manager have, so I can't really rely on a trait specifying each and every method type.
I've read about F-bound types / functions / what-not, but still couldn't figure out whether they are / how to make them applicable to my problem.
Any ideas? "Your restraing doesn't make sense" is also a possible answer, I reckon, but I'd like to get some ideas on this regardless.
I'm making the following assumptions:
When someone creates a manager, they know how many components they need.
One must declare versions for all components.
Traits have to declare all method names explicitly, so we can't declare methods for components we don't know about. Instead, let's model components as a type:
trait ComponentManager {
type Component
def version(component: Component): Version
}
When someone knows what components they need, they can implement a manager:
sealed trait MyComponent
case object Component1 extends MyComponent
case object Component2 extends MyComponent
case object Component3 extends MyComponent
object MyComponentManager extends ComponentManager {
type Component = MyComponent
def version(component: MyComponent): Version = component match {
case Component1 => Component1Version1()
case Component2 => Component2Version3()
case Component3 => Component3Version5()
}
}
Now:
Returning anything but a Version for any component is a type error.
Forgetting to match a component is a non-exhaustive match warning.

Preserve type/class tag among akka messages

I have the situation where I want to preserve information about some generic type passed within a message to be able to create another generic class with that same type within receive method responsible for processing the message.
At first glance I thought TypeTag is my best friend here, but, after trying that out it seems this is not the best possible solution, or not solution at all. Let me first explain what I have at the moment and what is the outcome.
Message case class
trait MessageTypeTag[T] {
def typeTag: TypeTag[T]
}
case class Message[T](id: Int, payload: T, helper: MyClass[T],
cond: Condition[MyClass[T]])(implicit val typeTag: TypeTag[T])
extends MessageTypeTag[T]
MyClass2
class MyClass2[+T <: Any](_eval: Option[T] = None) {
def getEval = _eval getOrElse None
}
Receive method
def receive() = {
case m#Message(id, payload, helper, cond) => {
// this prints a proper type tag, i.e. String, because type is known in the runtime
println(m.typeTag.tpe)
// compiler complains here because it sees m.typeTag as TypeTag[Any], i.e. exact
// type is not known in the compile time
val temp = new MyClass2[m.typeTag.tpe](...)
}
}
Dirty solution
After reading several articles, discussions, documentation on both Scala and akka I come up with some dirty solution by putting the (call to) factory method case class.
case class Message[T](id: Int, payload: T, helper: MyClass[T],
cond: Condition[MyClass[T]])(implicit val typeTag: TypeTag[T])
extends MessageTypeTag[T] {
def getMyClass2: MyClass2[T] = {
// instantiate an object of type T
val bla = typeTag.mirror.runtimeClass(typeTag.tpe).newInstance.asInstanceOf[T]
// we can call apply here to populate created object or do whathever is needed
...
// instantiate MyClass2 parametrized with type T and return it
new MyClass2[T](Some(bla))
}
}
As you can see this is far from good solution/design because this case class is all but lightweight and actually defeats the purpose of case class itself. It can be improved in a way that reflection call is not coded here but in some external factory which is just called within case class, but I have a feeling there must be a better approach to accomplish this.
Any suggestion would be very appreciated. If there are some more information needed, I can provide it.
And, I believe, similar problem/solution has been described here, but I'm wondering is there a better way. Thanks.
If you want to be able to instantiate a class with reflection then you have to pass it around, there's no way around that. I think a ClassTag based solution is slightly simpler:
val bla = classTag.runtimeClass.newInstance.asInstanceOf[T]
but it's still pretty ugly.
It might be better to pass around a factory as a function rather than using a reflective approach; this lets you work with classes with no no-arg constructor or that require some setup:
case class Message[T](..., factory: () => T) {
def getMyClass2 = new MyClass2[T](Some(factory()))
}
Message(..., {_ => new SomeTThatTakesArguments(3, 4)})
I suspect the best solution will be to change your MyClass2 so that it doesn't depend on the type in the same way - perhaps you can express the constraint MyClass2 needs as a typeclass you can include in the Message, or leave it out entirely. But you'll need to post MyClass2 if you want us to suggest a solution on those lines.

Scala Mock Object Creation

Is there a way to create an object of a given type that overrides a subset of methods and throws runtime exceptions for the rest of the methods?
It doesn't even need to have access to any implementation of the superclass. It just needs to have the same type at compiletime and runtime.
That pretty much is what a ScalaMock mock object does out of the box — methods you've set expectations on do whatever the expectations tell them to do, all others throw an ExpectationException.
What's your use-case?
As Paul said, ScalaMock is a good way to go.
But I wanted to point out that you're just describing basic inheritance:
class OriginalClass {
def methodToRun() = { println("called OriginalClass.methodToRun") }
def methodNotToRun() = { println("called OriginalClass.methodNotToRun") }
}
class MockOriginalClass extends OriginalClass {
override def methodToRun() = super.methodToRun()
override def methodNotToRun() = throw new RuntimeException("you weren't supposed to run this!")
}
Then, in your code, where you were expecting an OriginalClass object you can pass in a MockOriginalClass and it will throw errors when you call the wrong things.

Create specialised fields in Lift's Record Framework

One of the nice advantages of Scala is the way you can be type safe, so that no undefined values will appear in the application. Mongo, however, is not type safe at all. So, I thought, a kind of conversion to and from Mongo is good, to make sure only the right values are saved (as strings). I have this type in my Scala:
sealed trait Tribe
object Tribe {
def fromString(s:String) = s match {
case "Earth Pony" => EarthPony
case "Pegasus" => Pegasus
case "Unicorn" => Unicorn
case "Alicorn" => Alicorn
case _ => throw new NoSuchElementException
}
}
case object EarthPony extends Tribe {
override def toString = "Earth Pony"
}
case object Pegasus extends Tribe {
override def toString = "Pegasus"
}
case object Unicorn extends Tribe {
override def toString = "Unicorn"
}
case object Alicorn extends Tribe {
override def toString = "Alicorn"
}
Now I want to make a field TribeField which I can employ in a MongoRecord class to make sure this conversion is done when I read the Record, or save it.
Unfortunately, the documentation on Lift's Record seems sparse, and so far I have not found any helpful information on how to do this. Maybe someone here can give me some hints?
I'm fairly sure that lift-record-mongodb uses the ability of lift-record Field instances to serialize/deserialize to and from JSON via Field.asJValue and Field.setFromJValue. To make a completely type safe Tribe Field, you'd want to create your own TypedField[Tribe] and implement those methods along with the other abstract methods that set and access your field. I'd recommend taking a look at StringField or one of the other concrete Field types for pointers on how to do that.
An easier alternative would be to extend StringField itself and add setTribe/asTribe methods.
If you need more info, particularly on Lift's Mongodb integration, I'd recommend you try the Lift Google Group. Tim Nelson who maintains that code is usually pretty quick to respond to questions.

How do I declare a constructor for an 'object' class type in Scala? I.e., a one time operation for the singleton

I know that objects are treated pretty much like singletons in scala. However, I have been unable to find an elegant way to specify default behavior on initial instantiation. I can accomplish this by just putting code into the body of the object declaration but this seems overly hacky. Using an apply doesn't really work because it can be called multiple times and doesn't really make sense for this use case.
Any ideas on how to do this?
Classes and objects both run the code in their body upon instantiation, by design. Why is this "hacky"? It's how the language is supposed to work. If you like extra braces, you can always use them (and they'll keep local variables from being preserved and world-viewable).
object Initialized {
// Initalization block
{
val someStrings = List("A","Be","Sea")
someStrings.filter(_.contains('e')).foreach(s => println("Contains e: " + s))
}
def doSomething { println("I was initialized before you saw this.") }
}
scala> Initialized.doSomething
Contains e: Be
Contains e: Sea
I was initialized before you saw this.
scala> Initialized.someStrings
<console>:9: error: value someStrings is not a member of object Initialized
Initialized.someStrings
Rex has it right, I just wanted to point out a pattern I use a lot, that saves you from having to use vars, while avoiding namespace pollution by intermediate values.
object Foo {
val somethingFooNeeds = {
val intermediate = expensiveCalculation
val something = transform(intermediate)
something
}
}
If it makes you feel better, you can create some class with protected constructor and object will create singleton of this class:
sealed class MyClass protected (val a: String, b: Int) {
def doStuff = a + b
}
object MyObject extends MyClass("Hello", b = 1)
Also notice, that sealed stops other classes and objects to extend MyClass and protected will not allow creation of other MyClass instances.
But I personally don't see any problems with some code in the body of the object. You can also create some method like init and just call it:
object MyObject {
init()
def init() {
...
}
}
The body of object and class declarations IS the default constructor and any code placed in there will be executed upon first reference, so that is exactly the way to do it.