Scala generic class design - scala

So I have the following scenario. First a class hierarchy A <- B <- C
trait A
trait B extends A
class C extends B
I also have a class that has a generic parameter defined as [T <: A]
class Foo[T <: A]
This class defines two methods that accept objects of type T
def single(t: T): Bar
def multiple(lt: List[T]): Bars
If the objects t and lt are of a type derived from B both, of these methods call another method that takes t and lt (mapping over its elements), does some modification to it (which depends on the type itself) and spits the same object out
def update[P <: B](op: P, item: Item): P = {
if (item.field1..) op.field1 = item.field1
if (item.field2..) op.field2 = item.field2
...
op match {
case c: C =>
if (item.field123 ...) c.field123 = item.field123
}
op
}
I don't like the way this method is right now as it does mutation on the objects. As I am following a functional programming style I have managed to keep the codebase immutable and composable.
I would prefer to push the field assignments to constructors and build up the objects based on their parent class but due to Scala's auxiliary constructor calling scheme I cannot find a way to do this. Another way would have been to have a case class and use the copy constructor but I cannot do that because I need to keep A, B and C extendable.
I hope I managed to describe my scenario well enough. If you need some more clarification - please ask. I would appreciate any help with this one.

Typeclasses to the rescue
object Example {
trait Item
// generic interface that makes possible for T
// to be updated by an Item
// Better to return a new object here instead of mutating an old one
trait Updater[T] {
def update(obj: T, item: Item): T
}
class B1
class B2
implicit val b1Updated: Updater[B1] = new Updater[B1] {
override def update(obj: B1, item: Item): B1 = {
println("B1 updater called")
//your code for b1 here
???
}
}
implicit val b2Updated: Updater[B2] = new Updater[B2] {
override def update(obj: B2, item: Item): B2 = {
println("B2 updater called")
//your code for b2 here
???
}
}
//whenever you add a new class that has to be updatable you must provide such instance of Updater[MyNewB]
//But you don't have to declare it right here so it's still modular
//works for every type T that has implicit instance of type Updater[T]
def updateOne[T: Updater](obj: T, item: Item): T = {
implicitly[Updater[T]].update(obj, item)
}
def updateList[T: Updater](lst: List[T], item: Item): List[T] = {
val updater = implicitly[Updater[T]]
lst.map(e => updater.update(e, item))
}
def main(args: Array[String]): Unit = {
val list: List[B1] = List(new B1, new B1)
updateList(list, new Item {})
}
}

Related

Specify concrete type for methods in Scala trait

I want to define a method in a Scala trait where both a parameter to the method and the return type correspond to the same concrete class which extends the trait. I've tried something like the following:
trait A {
def foo(obj: this.type): this.type
}
final case class B(val bar: Int) extends A {
override def foo(obj: B): B = {
B(obj.bar + this.bar)
}
}
object Main {
def main(args: Array[String]) = {
val b1 = new B(0)
val b2 = new B(0)
val b3: B = b1.foo(b2)
}
}
However, trying to compile this code gives the following error:
Test.scala:5: error: class B needs to be abstract. Missing implementation for:
def foo(obj: B.this.type): B.this.type // inherited from trait A
case class B(val bar: Int) extends A {
^
Test.scala:6: error: method foo overrides nothing.
Note: the super classes of class B contain the following, non final members named foo:
def foo: ((obj: _1.type): _1.type) forSome { val _1: B }
override def foo(obj: B): B = {
^
2 errors
There's obviously something I'm misunderstanding about the Scala type system here. The signature of foo in class B is what I want it to be, but I don't know how to correctly define the method in A (or if this is even possible). It seems like this question is asking something quite similar, but I don't immediately see how the answer applies in my situation.
The type annotation this.type means that you may only return this. So in that case you may not return another instance of B, the same holds for the method parameter.
If this was just about the return type, a solution would be to require foo to return something of type A, the override method in B can specialize the return type to return B.
However since you also have an argument which you want to be of the type of the subtype you could use a Self Recursive Type. The following example compiles and should do what you want.
trait A[S <: A[S]] {
def foo(obj: S): S
}
case class B(val bar: Int) extends A[B] {
override def foo(obj: B): B = {
B(obj.bar + 1)
}
}
Consider type class solution
case class B(bar: Int)
// type class
trait Fooable[A] {
def foo(x: A, y: A): A
}
// proof that B satisfies Fooable constraints
implicit val fooableB: Fooable[B] = new Fooable[B] {
override def foo(x: B, y: B): B = B(x.bar + y.bar)
}
// a bit of syntax sugar to enable x foo y
implicit class FooableOps[A](x: A) {
def foo(y: A)(implicit ev: Fooable[A]) = ev.foo(x,y)
}
val b1 = B(1)
val b2 = B(41)
b1.foo(b2)
// B(42)
which Scala 3 simplifies to
case class B(bar: Int)
// type class
trait Fooable[A] {
extension (x: A) def foo (y: A): A
}
// proof that B satisfies Fooable constraints + syntactic sugar
given Fooable[B] with
extension (x: B) def foo (y: B): B = B(x.bar + y.bar)
val b1 = B(1)
val b2 = B(41)
b1.foo(b2)
// B(42)
See Scala FAQ: How can a method in a superclass return a value of the “current” type?

Scala change parameters of function defined in trait

Because I didn't find a solution to my problem anywhere, I think I might be thinking into a very wrong direction.
Here's my problem:
I have a trait A and another trait B and companion objects AB1, AB2, AB3 and so on. The singleton objects extend trait A and the classes extend trait B. Many objects of those classes are in a list.
On these objects I want to use functions defined in the corresponding singleton object which take objects of the same class as the singleton object is.
This an example for the traits:
trait A {
def compare(firstB: B, secondB: B) : Int
}
trait B {}
And the companion objects:
class AB1(val variable: Int) extends B {}
object AB1 extends A {
def apply(list: List[Int]): Option[AB1] = {
if(list.foldLeft(0)(_ + _) < 10 && list.nonEmpty)
some(new AB1(list.head))
else
null
}
override def compare(ab11: AB1, ab12: AB1): Int = {
if(ab11 > ab12)
1
else if(ab11 > ab12)
-1
else
0
}
}
and
class AB2(val variable1: Int, val variable2: Int) extends B {}
object AB2 extends A {
def apply(list: List[Int]): Option[AB1] = {
if(list.foldLeft(0)(_ + _) < 20 && list.length >= 2)
some(new AB1(list.head, list.tail.head))
else
null
}
override def compare(ab21: AB2, ab22: AB2): Int = {
if(ab11 > ab12)
10
else if(ab11 > ab12)
-10
else
0
}
}
So I've already filtered the some objects and put the "real" objects into a list, let's call it bList. On every element of the list I want to call the compare function.
I think it would look something like this:
val bList: List[B]
val a = getA(bList.head) // getA should be a function that returns the companion object of a class
a.compare(bList.head, bList.tail.head)
On my way I encountered two problems:
b.getClass does not equal AB1.getClass when b is an object the class AB1. But this is not my main problem. I found a solution using String comparison, which really is not pretty, but for now, it works.
The compare function has to be defined in the trait, because otherwise it can't be casted on any singleton object that extends trait A. But I find no way to define the function with parameters of a variable type.
I really hope you can help me with this problem!
EDIT: Now I see that I've forgotten to mention something:
I think that I have to go a bit deeper into what I am trying to do to make you understand my problem:
I have a List[List[C]]. A List of those C's may be capable of creating an AB1 object with it but maybe AB2, or maybe AB3 and so on. So I have
val c: List[C] = (C1, C2, C4)
val aList: List[A] = (AB1, AB2, AB3, ...)
val bestB: B = (for{
element <- aList
} yield element (c)).flatten.head // Because the List aList is ordered: AB1 is the best case, AB2 the second best and so on.
I do that for every List[C] out of the List[List[C]]. So in the end I may have a List[B] = (AB3, AB1, AB2, AB1) (for example). From this list I want to get the "best" Bs according to the order of aList at first - then i get List[B] = (AB1, AB1). These two AB1's I want to compare and then put the "better" Element (according to the compare function of the corresponding object) or both into a new list. This is want I want to accomplish.
To be honest, I'm still confused with what is your root problem. But I will try to answer what I understood.
First, if you want to change the type of the arguments when overriding a function from a trait. Then, the answer is you can't! - Because that would break the Liskov Substitution Principle.
But you can achieve what you want with a Type Class .
trait B {}
trait BComparator[Bi <: B] {
def compare(firstB: Bi, secondB: Bi): Int
}
Now if you want a way to dynamically obtain the right instance of the BComparator for your sub-classes you could make those instances as implicit values in their companion objects.
class B1 extends B {}
object B1 {
implicit val B1Comparator: BComparator[B1] = new BComparator[B1] {
override def compare(firstB: B1, secondB: B2): Int = ???
}
}
Now, given b11 and b12 as instances of B1 you could just write
implicitly[BComparator[B1]].compare(b11, b12)
I think you need to use implicit Comparator:
trait B
case class AB1(variable: Int) extends B
case class AB2(variable1: Int, variable2: Int) extends B
implicit object AB1Comparator extends Comparator[AB1] {
override def compare(o1: AB1, o2: AB1): Int = java.lang.Integer.compare(o1.variable, o2.variable)
}
implicit object AB2Comparator extends Comparator[AB2] {
override def compare(o1: AB2, o2: AB2): Int = java.lang.Integer.compare(o1.variable1, o2.variable1) match {
case 0 => java.lang.Integer.compare(o1.variable2, o2.variable2)
case other => other
}
}
def compare[A](obj1: A, obj2: A)(implicit comparator: Comparator[A]) = {
comparator.compare(obj1, obj2)
}
val ab1List = List(AB1(1), AB1(2), AB1(3))
val ab1Compare = compare(ab1List.head, ab1List.tail.head)
val ab2List = List(AB2(1, 1), AB2(1, 1), AB2(1, 3))
val ab2Compare = compare(ab2List.head, ab2List.tail.head)
Or if you want to sort list you should use Ordering:
trait B
case class AB1(variable: Int) extends B
implicit object AB1Ordering extends Ordering[AB1] {
override def compare(o1: AB1, o2: AB1): Int = java.lang.Integer.compare(o1.variable, o2.variable)
}
val ab1List = List(AB1(1), AB1(2), AB1(3))
val ab1ListSorted = ab1List.sorted

Override implicit vals from trait

I need overriding implicit in object res defing one from trait. The purpose is to define custom implicits in one place (trait B). Trait a is defined in external library. Is it possible?
trait t {
}
object m extends t
object q extends t
trait a {
implicit val o: t = m
}
trait b {
implicit val o: t = q
}
trait c {
def action(implicit v: t): Unit = {}
}
object res extends c with a with b {
//i need smth like override val o = super[b].o
val ololo= action
}
It is not possible to mix-in two unrelated traits that both contain a member with the same identifier. The Scala compiler has no way to resolve which one would take precedence in this scenario. Since types A and B are related, o does not even need to have the same type in both of them. Trait B needs to extend A and override o. There isn't any other way to override a member without using inheritance.
trait T
case object M extends T
case object Q extends T
trait A {
implicit val o: T = M
}
trait B extends A {
override implicit val o: T = Q
}
trait C {
def action(implicit v: T): Unit = println(v)
}
object Res extends C with B {
def call() = action
}
scala> Res.call()
Q
Since you are already mixing A into Res anyway, it is assumed that A is not difficult to extend, since Res must implement any other unmentioned abstract members.

Type inference for nested types in Scala

I want to write a generic class that takes a nested type. The outer type (I) has to extend Iterable, and the inner type (M) can be anything.
Here is the example I have:
// The outer type here is I and the inner type is M
class GenericDistributor[I <: Iterable[M], M] {
def map(input: I): Unit = {
input.foreach(item => {
//do some stuff
})
}
}
class IntegerGroup(id: Int, items: Set[Int]) extends Iterable[Int] {
override def iterator: Iterator[Int] = items.iterator
}
object IntegerGroupDistributor extends GenericDistributor[IntegerGroup, Int]
val integerGroup = new IntegerGroup(1, Set(1,2,3))
IntegerGroupDistributor.map(integerGroup)
The problem is that I have to explicitly define the inner type M in the GenericDistributor class which I do not want to. Is there a way for Scala to automatically infer the inner type given the outer type?
EDIT
According to the comment of #Arioch. I tried duck types and that seems to fix my problem but still I feel there should be neater way.
class GenericDistributor[I <: {type M; def iterator: Iterator[M]}] {
def map(input: I): Unit = {
val it: Iterator[M] = input.iterator
it.foreach(println)
}
}
class IntegerGroup(id: Int, items: Set[Int]) extends Iterable[Int] {
type M = Int
override def iterator: Iterator[Int] = items.iterator
}
object IntegerGroupDistributor extends GenericDistributor[IntegerGroup]
If you don't need to use any custom methods of type I, your external class need only be parameterized on M. The Iterator[M] does not needed to be added separately since you already have all you need to define it from M.
class GenericDistributor[M] {
type I = Iterable[M]
def map(input: I): Unit = {
input.foreach(item => {
//do some stuff
})
}
}
If you only want a single type parameter there are two options:
(1) State that you do not care about the iterator's type
class GenericDistributor[I <: Iterable[_]]
(2) Use an implicit to store the inner type
class GenericDistributor[I : IterableInfo]
// or (equivalently)
class GenericDistributor[I]()(implicit i: IterableInfo[I])
trait IterableInfo[I] {
type Element
}
object IterableInfo {
implicit def forIterable[I <: Iterable[M], M]: IterableInfo[I] { type Element = M } = ...
}
The last option allows you to shape your code in a lot of different ways. You could add methods to IterableInfo, you could add type members, you could add a restriction of Iterable to the I type parameter.

Minimal framework in Scala for collections with inheriting return type

Suppose one wants to build a novel generic class, Novel[A]. This class will contain lots of useful methods--perhaps it is a type of collection--and therefore you want to subclass it. But you want the methods to return the type of the subclass, not the original type. In Scala 2.8, what is the minimal amount of work one has to do so that methods of that class will return the relevant subclass, not the original? For example,
class Novel[A] /* What goes here? */ {
/* Must you have stuff here? */
def reverse/* What goes here instead of :Novel[A]? */ = //...
def revrev/*?*/ = reverse.reverse
}
class ShortStory[A] extends Novel[A] /* What goes here? */ {
override def reverse: /*?*/ = //...
}
val ss = new ShortStory[String]
val ss2 = ss.revrev // Type had better be ShortStory[String], not Novel[String]
Does this minimal amount change if you want Novel to be covariant?
(The 2.8 collections do this among other things, but they also play with return types in more fancy (and useful) ways--the question is how little framework one can get away with if one only wants this subtypes-always-return-subtypes feature.)
Edit: Assume in the code above that reverse makes a copy. If one does in-place modification and then returns oneself, one can use this.type, but that doesn't work because the copy is not this.
Arjan linked to another question that suggests the following solution:
def reverse: this.type = {
/*creation of new object*/.asInstanceOf[this.type]
}
which basically lies to the type system in order to get what we want. But this isn't really a solution, because now that we've lied to the type system, the compiler can't help us make sure that we really do get a ShortStory back when we think we do. (For example, we wouldn't have to override reverse in the example above to make the compiler happy, but our types wouldn't be what we wanted.)
Edit: I just realized that Rex had a concrete class Novel in his example, not a trait as I've used below. The trait implementation is a bit too simple to be a solution to Rex's question, therefore. It can be done as well using a concrete class (see below), but the only way I could make that work is by some casting, which makes this not really 'compile time type-safe'. This So this does not qualify as a solution.
Perhaps not the prettiest, but a simple example using abstract member types could be implemented as follows:
trait Novel[A] {
type T <: Novel[A]
def reverse : T
def revrev : T#T = reverse.reverse
}
class ShortStory[A](var story: String) extends Novel[A] {
type T = ShortStory[A]
def reverse : T = new ShortStory[A](story reverse)
def myMethod: Unit = println("a short story method")
}
scala> val ss1 = new ShortStory[String]("the story so far")
ss1: ShortStory[String] = ShortStory#5debf305
scala> val ssRev = ss1 reverse
ssRev: ss1.T = ShortStory#5ae9581b
scala> ssRev story
res0: String = raf os yrots eht
scala> val ssRevRev = ss1 revrev
ssRevRev: ss1.T#T = ShortStory#2429de03
scala> ssRevRev story
res1: String = the story so far
scala> ssRevRev myMethod
a short story method
It's certainly minimal, but I doubt whether this would enough to be used as a kind of framework. And of course the types returned not anywhere near as clear as in the Scala collections framework, so perhaps this might be a bit too simple. For the given case, it seems to do the job, however. As remarked above, this does not do the job for the given case, so some other solution is required here.
Yet Another Edit: Something similar can be done using a concrete class as well, though that also not suffices to be type safe:
class Novel[A](var story: String) {
type T <: Novel[A]
def reverse: T = new Novel[A](story reverse).asInstanceOf[T]
def revrev : T#T = reverse.reverse
}
class ShortStory[A](var s: String) extends Novel[A](s) {
type T = ShortStory[A]
override def reverse : T = new ShortStory(story reverse)
def myMethod: Unit = println("a short story method")
}
And the code will work as in the trait example. But it suffers from the same problem as Rex mentioned in his edit as well. The override on ShortStory is not necessary to make this compile. However, it will fail at runtime if you don't do this and call the reverse method on a ShortStory instance.
I haven't thought this through fully, but it type checks:
object invariant {
trait Novel[A] {
type Repr[X] <: Novel[X]
def reverse: Repr[A]
def revrev: Repr[A]#Repr[A]
= reverse.reverse
}
class ShortStory[A] extends Novel[A] {
type Repr[X] = ShortStory[X]
def reverse = this
}
val ss = new ShortStory[String]
val ss2: ShortStory[String] = ss.revrev
}
object covariant {
trait Novel[+A] {
type Repr[X] <: Novel[_ <: X]
def reverse: Repr[_ <: A]
def revrev: Repr[_ <: A]#Repr[_ <: A] = reverse.reverse
}
class ShortStory[+A] extends Novel[A] {
type Repr[X] = ShortStory[X]
def reverse = this
}
val ss = new ShortStory[String]
val ss2: ShortStory[String] = ss.revrev
}
EDIT
The co-variant version can be much nicer:
object covariant2 {
trait Novel[+A] {
type Repr[+X] <: Novel[X]
def reverse: Repr[A]
def revrev: Repr[A]#Repr[A] = reverse.reverse
}
class ShortStory[+A] extends Novel[A] {
type Repr[+X] = ShortStory[X]
def reverse = this
}
val ss = new ShortStory[String]
val ss2: ShortStory[String] = ss.revrev
}
After discussions on the Scala mailing list--many thanks to the people there for setting me on the right track!--I think that this is the closest that one can come to a minimal framework. I leave it here for reference, and I'm using a different example because it highlights what is going on better:
abstract class Peano[A,MyType <: Peano[A,MyType]](a: A, f: A=>A) {
self: MyType =>
def newPeano(a: A, f: A=>A): MyType
def succ: MyType = newPeano(f(a),f)
def count(n: Int): MyType = {
if (n<1) this
else if (n==1) succ
else count(n-1).succ
}
def value = a
}
abstract class Peano2[A,MyType <: Peano2[A,MyType]](a: A, f: A=>A, g: A=>A) extends Peano[A,MyType](a,f) {
self: MyType =>
def newPeano2(a: A, f: A=>A, g: A=>A): MyType
def newPeano(a: A, f: A=>A): MyType = newPeano2(a,f,g)
def pred: MyType = newPeano2(g(a),f,g)
def uncount(n: Int): MyType = {
if (n < 1) this
else if (n==1) pred
else uncount(n-1).pred
}
}
The key here is the addition of the MyType type parameter that is a placeholder for the type of the class that we'll really end up with. Each time we inherit, we have to redefine it as a type parameter, and we have add a constructor method that will create a new object of this type. If the constructor changes, we have to create a new constructor method.
Now when you want to create a class to actually use, you only have to fill in the constructor method with a call to new (and tell the class that it's of its own type):
class Peano2Impl[A](a: A, f: A=>A, g: A=>A) extends Peano2[A,Peano2Impl[A]](a,f,g) {
def newPeano2(a: A, f: A=>A, g: A=>A) = new Peano2Impl[A](a,f,g)
}
and you're off and running:
val p = new Peano2Impl(0L , (x:Long)=>x+1 , (y:Long)=>x-1)
scala> p.succ.value
res0: Long = 1
scala> p.pred.value
res1: Long = -1
scala> p.count(15).uncount(7).value
res2: Long = 8
So, to review, the minimal boilerplate--if you want to include recursive methods, which breaks the other style of answer--is for any methods that return a new copy from outside the class (using new or a factory or whatever) to be left abstract (here, I've boiled everything down to one method that duplicates the constructor), and you have to add the MyType type annotation as shown. Then, at the final step, these new-copy methods have to be instantiated.
This strategy works fine for covariance in A also, except that this particular example doesn't work since f and g are not covariant.