Problems using Nothing bottom type while trying to create generic zeros for parametrized monoids - mongodb

Here's my code. It permits to create typesafe MongoDB queries using Casbah
trait TypesafeQuery[ObjectType, BuildType] {
def build: BuildType
}
trait TypesafeMongoQuery[ObjectType] extends TypesafeQuery[ObjectType, DBObject]
case class TypesafeMongoQueryConjunction[ObjectType](queries: Seq[TypesafeMongoQuery[ObjectType]]) extends TypesafeMongoQuery[ObjectType] {
override def build(): DBObject = $and(queries.map(_.build))
}
case class TypesafeMongoQueryDisjunction[ObjectType](queries: Seq[TypesafeMongoQuery[ObjectType]]) extends TypesafeMongoQuery[ObjectType] {
override def build(): DBObject = $or(queries.map(_.build))
}
object TypesafeMongoQuery {
// TODO could probably be reworked? see http://stackoverflow.com/questions/23917459/best-way-to-create-a-mongo-expression-that-never-matches
val AlwaysMatchingQuery: DBObject = $()
val NeverMatchingQuery: DBObject = $and($("_id" -> 1), $("_id" -> -1))
def AlwaysMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = AlwaysMatchingQuery }
def NeverMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = NeverMatchingQuery }
def and[ObjectType](queries: TypesafeMongoQuery[ObjectType]*) = TypesafeMongoQueryConjunction(queries)
def or[ObjectType](queries: TypesafeMongoQuery[ObjectType]*) = TypesafeMongoQueryDisjunction(queries)
// TODO maybe define Scalaz Monoids
def foldAnd[ObjectType](queries: Seq[TypesafeMongoQuery[ObjectType]]) = {
queries.foldLeft(AlwaysMatchingTypesafeQuery[ObjectType]) { (currentQuery, queryInList) =>
TypesafeMongoQuery.and(currentQuery, queryInList)
}
}
def foldOr[ObjectType](base: TypesafeMongoQuery[ObjectType], queries: Seq[TypesafeMongoQuery[ObjectType]]) = {
queries.foldLeft(NeverMatchingTypesafeQuery[ObjectType]) { (currentQuery, queryInList) =>
TypesafeMongoQuery.or(currentQuery, queryInList)
}
}
}
It works fine, except I'm not satisfied with these lines:
def AlwaysMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = AlwaysMatchingQuery }
def NeverMatchingTypesafeQuery[ObjectType] = new TypesafeMongoQuery[ObjectType] { override def build(): DBObject = NeverMatchingQuery }
I think It would be possible to not create a new instance of these 2 objects for each folding operation, but rather using a val / singleton of type TypesafeMongoQuery[Nothing] since the underlying DBObject being built would always be the same.
I've tried some things, like replacing my signatures everywhere by [ObjectType,T <% ObjectType] but with no great success.
Any idea on how to solve my problem?

Can you make ObjectType covariant?
trait TypesafeQuery[+ObjectType, BuildType] {
def build: BuildType
}
trait TypesafeMongoQuery[+ObjectType] extends TypesafeQuery[+ObjectType, DBObject]
object AlwaysMatchingTypesafeQuery extends TypesafeMongoQuery[Nothing] { override def build(): DBObject = AlwaysMatchingQuery }
object NeverMatchingTypesafeQuery extends TypesafeMongoQuery[Nothing] { override def build(): DBObject = NeverMatchingQuery }

Related

Syntax extension using type class methods in Scala

I want to bind a check method to the Test in such a way that the implementation does not contain an argument (look at the last line). It is necessary to use type classes here, but I'm new in Scala, so I have problems.
Object Checker is my attempts to solve the problem. Perhaps it is enough to make changes to it...
trait Test[+T] extends Iterable[T]
class TestIterable[+T](iterable: Iterable[T]) extends Test[T] {
override def iterator: Iterator[T] = iterable.iterator
}
object Test {
def apply[T](iterable: Iterable[T]): Test[T] = new TestIterable[T](iterable)
}
trait Check[M] {
def check(m: M): M
}
object Checker {
def apply[M](implicit instance: Check[M]): Check[M] = instance
implicit def checkSyntax[M: Check](m: M): CheckOps[M] = new CheckOps[M](m)
private implicit def test[T](m: Test[T]) : Check[Test[T]] = {
new Check[Test[T]] {
override def check(m: Test[T]) = m
}
}
final class CheckOps[M: Check](m: M) {
def x2: M = Checker[M].check(m)
}
}
import Checker._
val test123 = Test(Seq(1, 2, 3))
Test(test123).check

Return a child class from apply method of base trait

I'm struggling to understand if it possible for a apply function to return an instance of a specific class. Here is an example:
I have an abstract trait
trait BaseTrait {
def add(s: Int): Int
}
and two classes that inherit this trait and:
override an abstract method
specify a method another_method
class Child1 extends BaseTrait {
override def add(s: Int): Int = {
s + s
}
def another_method(): Unit = {
println("Another method in Child1")
}
}
class Child2 extends BaseTrait {
override def add(s: Int): Int = {
s + s
}
def another_method(): Unit = {
println("Another method in Child2")
}
}
When I try to access the contents of child classes from a utility function in a Base Trait
object BaseTrait {
def apply(t: String): BaseTrait = {
t match {
case "one" => new Child1()
case "two" => new Child2()
}
}
}
val child2 = BaseTrait("one")
i don't see another_method method
child2.another_method() // cannot resolve symbol another method
Question: is there a way in Scala (generics/lower-upper bounds) to configure an apply method in such a way that it returns an instances of classes where it will be possible to access both overridden abstract methods AND methods belonging to this exact class (not just those that are defined in BaseTrait)
In this particular case you could try literal types
object BaseTrait {
def apply(t: "one"): Child1 = new Child1()
def apply(t: "two"): Child2 = new Child2()
}
val child1 = BaseTrait("one")
child1.another_method()
// Another method in Child1
Besides overloading you can also try a type class
object BaseTrait {
def apply[S <: String with Singleton](t: S)(implicit tc: MyTypeclass[S]): tc.Out = tc()
}
trait MyTypeclass[S <: String] {
type Out <: BaseTrait
def apply(): Out
}
object MyTypeclass {
implicit val one = new MyTypeclass["one"] {
override type Out = Child1
override def apply() = new Child1()
}
implicit val two = new MyTypeclass["two"] {
override type Out = Child2
override def apply() = new Child2()
}
}
val child2 = BaseTrait("one")
child2.another_method()
(Scala 2.13)

Immutable composable builder in scala

I'm interested how to improve the piece of code bellow. The idea is to build an immutable composable builder. In the end the builder just builds a Map[String, Object]. I want to be able to define core builder components that can be reused and to also let people define their own additional builders to extend the main builder. I'm able to do so but not without the ugly use of reflection. The code looks as follows:
object TestPizzaBuilder {
def main(args: Array[String]): Unit = {
val build = new PizzaBuilder()
.withCheese("blue")
.withSauce("tomato")
.build()
println(build)
}
}
object PizzaBuilder {
type BuilderParams = Map[String, Object]
}
class PizzaBuilder(params: BuilderParams = Map.empty) extends BaseBuilder[PizzaBuilder](params: BuilderParams)
with CheeseBuilder[PizzaBuilder]
with SauceBuilder[PizzaBuilder] {
}
abstract class BaseBuilder[A <: BaseBuilder[A]](params: BuilderParams)(implicit tag: ClassTag[A]) {
protected def _copy(tuples: (String, Object)*): A = {
val constr = tag.runtimeClass.getConstructors()(0)
constr.newInstance(params ++ tuples).asInstanceOf[A]
}
def build(): Map[String, Object] = {
params
}
}
trait CheeseBuilder[A <: BaseBuilder[A]] {
this: BaseBuilder[A] =>
def withCheese(cheese: String): A = _copy("cheese" -> cheese)
}
trait SauceBuilder[A <: BaseBuilder[A]] {
this: BaseBuilder[A] =>
def withSauce(sauce: String): A = _copy("sauce" -> sauce)
}
Do you have suggestions how reflection can be avoided in this scenario yet keeping the builder immutable and also allowing to compose the builder of tiny other builders.
Smallest change would be to pass the constructor (as a function) instead of a ClassTag:
abstract class BaseBuilder[A <: BaseBuilder[A]](params: BuilderParams)(constructor: BuilderParams => A) {
protected def _copy(tuples: (String, Object)*): A = constructor(params ++ tuples)
def build(): Map[String, Object] = {
params
}
}
// or class PizzaBuilder(params: BuilderParams = Map.empty) extends BaseBuilder[PizzaBuilder](params)(new PizzaBuilder(_))
case class PizzaBuilder(params: BuilderParams = Map.empty) extends BaseBuilder[PizzaBuilder](params)(PizzaBuilder)
with CheeseBuilder[PizzaBuilder]
with SauceBuilder[PizzaBuilder] {
}

stack overflow on overriding lazy val in scala

I have trimmed my code down to the following. I am confused why I am getting a stack overflow between the two filter methods (one in my trait and one in my superclass)
object TestingOutTraits {
val TestHandler = new Object with MySuper with MyTrait {
override lazy val createdFilter = {
"second part"
}
}
def main(args: Array[String]) = {
val result : String = TestHandler.start()
System.out.println("result="+result)
}
}
trait MySuper {
protected def filter: String = {
"first part to->"
}
def start() = {
filter
}
}
trait MyTrait { self: MySuper =>
lazy val createdFilter = {
"override this"
}
protected override def filter: String = {
self.filter + createdFilter
}
}
This is scala 2.9. Any ideas what is going on here?
EDIT:
The stack trace makes no sense on how it jumps back and forth too(I should have included it in original post)...
at MyTrait$class.filter(TestingOutTraits.scala:34)
at TestingOutTraits$$anon$1.filter(TestingOutTraits.scala:4)
at MyTrait$class.filter(TestingOutTraits.scala:34)
at TestingOutTraits$$anon$1.filter(TestingOutTraits.scala:4)
thanks,
Dean
The call self.filter in MyTrait.filter invokes itself, leading to infinite recursion that blows the stack.
Instead, have MyTrait extend MySuper, and use super.filter:
trait MyTrait extends MySuper {
lazy val createdFilter = {
"override this"
}
protected override def filter: String = {
super.filter + createdFilter
}
}
Alternatively,
trait MySuper extends Filtered {
protected def filter: String = {
"first part to->"
}
def start() = {
filter
}
}
trait Filtered {
protected def filter: String
}
trait MyTrait extends Filtered {
lazy val createdFilter = {
"override this"
}
protected abstract override def filter: String = {
super.filter + createdFilter
}
}
then
val nope = new MyTrait { } // correctly DNC
and the OP
val TestHandler = new MySuper with MyTrait {
override lazy val createdFilter = {
"second part"
}
}
http://www.artima.com/pins1ed/traits.html#12.5
Well, I know why the infinite recursion though this seems like a linearization bug in scala and I am not sure how to work around it yet either :(.
hmmmm, so it turns out the compiler is sticking a filter method in my new Object for some reason. I found this out with the print:mixin on scalac like so
$ scalac -Xprint:mixin TestingOutTraits.scala
[[syntax trees at end of mixin]]// Scala source: TestingOutTraits.scala
package <empty> {
final object TestingOutTraits extends java.lang.Object with ScalaObject {
private[this] val TestHandler: MySuper = _;
<stable> <accessor> def TestHandler(): MySuper = TestingOutTraits.this.TestHandler;
def main(args: Array[java.lang.String]): Unit = {
val result: java.lang.String = TestingOutTraits.this.TestHandler().start();
java.this.lang.System.out.println("result=".+(result))
};
def this(): object TestingOutTraits = {
TestingOutTraits.super.this();
TestingOutTraits.this.TestHandler = {
new anonymous class TestingOutTraits$$anon$1()
};
()
}
};
abstract trait MySuper extends java.lang.Object with ScalaObject {
def filter(): java.lang.String;
def start(): java.lang.String
};
abstract trait MyTrait extends java.lang.Object with ScalaObject { self: MyTrait =>
def createdFilter(): java.lang.String;
override def filter(): java.lang.String
};
abstract trait MySuper$class extends {
def filter($this: MySuper): java.lang.String = "first part to->";
def start($this: MySuper): java.lang.String = $this.filter();
def /*MySuper$class*/$init$($this: MySuper): Unit = {
()
}
};
abstract trait MyTrait$class extends { self: MyTrait =>
def createdFilter($this: MyTrait): java.lang.String = "override this";
override def filter($this: MyTrait): java.lang.String = $this.$asInstanceOf[MySuper]().filter().+($this.createdFilter());
def /*MyTrait$class*/$init$($this: MyTrait): Unit = {
()
}
};
final class TestingOutTraits$$anon$1 extends java.lang.Object with MySuper with MyTrait {
override def filter(): java.lang.String = MyTrait$class.filter(TestingOutTraits$$anon$1.this);
def start(): java.lang.String = MySuper$class.start(TestingOutTraits$$anon$1.this);
override def createdFilter(): java.lang.String = "second part";
def this(): anonymous class TestingOutTraits$$anon$1 = {
TestingOutTraits$$anon$1.super.this();
MySuper$class./*MySuper$class*/$init$(TestingOutTraits$$anon$1.this);
MyTrait$class./*MyTrait$class*/$init$(TestingOutTraits$$anon$1.this);
()
}
}

simple scala macro

I would like to have a scala macro that does the following:
When I write:
myCreateCityMacro("paris")
myCreateCityMacro("vallorbe")
I would like to get:
val paris = new City("paris")
val vallorbe = new City("vallorbe")
This can be solved using scala Dynamic feature:
import scala.language.dynamics
object Cities extends App {
var c = new DynamicMap[String, City]()
createCity("Paris")
createCity("Vallorbe")
println(c.Paris, c.Vallorbe)
def createCity(name: String) {
c.self.update(name, new City(name))
}
}
class City(name: String) {
override def toString = s"-[$name]-"
}
class DynamicMap[K, V] extends Dynamic {
val self = scala.collection.mutable.Map[K, V]()
def selectDynamic(key: K) = self(key)
}
when executing:
(-[Paris]-,-[Vallorbe]-)