Here is a simplification of what I encountered. This compiles:
trait A { implicit val x = 1 }
trait B extends A { val y = implicitly[Int] }
While this don't (could not find implicit value):
trait B extends A { val y = implicitly[Int] }
trait A { implicit val x = 1 }
I tried to make my intentions clear by specifying a self-type: trait A { this: B => ... }, but to no avail.
How do I deal with this kind of dependencies without worrying about how my code is laid out?
You need to declare the type explicitly, at least for the latter one
trait B extends A { val y = implicitly[Int] }
trait A { implicit val x : Int = 1 }
The rules for implicit visibility is different whether its type is declared explicitely or not. If it is not, the implicit is available (as an implicit) only after the point of declaration.
The reason is that type inference may become too difficult if the type was not declared (as in recursive routine). In many cases, inference would be easy (as in your code) but the spec has to be clear cut.
Related
I have a simple trait that requires the implementation to have a method quality(x:A) which I want to return an Ordered[B]. In other words, quality transforms A to Ordered[B]. Such that I can compare to B's.
I have the following basic code:
trait Foo[A] {
def quality[B](x:A):Ordered[B]
def baz(x1:A, x2:A) = {
// some algorithm work here, and then
if (quality(x1) > quality(x2)) {
// some stuff
}
}
Which I want to implement like follows:
class FooImpl extends Foo[Bar] {
def quality(x:Bar):Double = {
someDifficultQualityCalculationWhichReturnsADouble
}
}
I figured this could work because Double is implicitly converted to RichDouble which implements Ordered[Double] if I am correct.
But at the > in the baz method of the trait it gives me an error of quality(x2) stating: Type mismatch, expected Nothing, actual Ordered[Nothing]
I do not understand this, because, coming from C#, I find it comparable to returning something like IEnumerable<A> and then using al the nice extension methods of an IEnumerable.
What am I missing here? What I want to to with the trait is define a complex algorithm inside the trait, but the key functions need to be defined by the class implementing the trait. On of these functions is needed to calculate a quality factor. This can be a Double, Int or whatnot but it can also be something more sophisticated. I could rewrite it that it always returns Double and that is certainly possible, but I want the trait to be as generic as possible because I want it to describe behavior and not implementation. I thought about the class A implementing Ordered[A] but that also seems weird, because it is not the 'purpose' of this class to be compared.
Using Ordering[A] you can compare As without requiring A to implement Ordered[A].
We can request that an Ordering[A] exists in baz by adding an implicit parameter :
trait Foo[A] {
def baz(x1:A, x2:A)(implicit ord: Ordering[A]) =
if (ord.gt(x1, x2)) "first is bigger"
else "first is smaller or equal"
}
Lets create a Person case class with an Ordering in its companion object.
case class Person(name: String, age: Int)
object Person {
implicit val orderByAge = Ordering.by[Person, Int](_.age)
}
We can now use Foo[Person].baz because an Ordering[Person] exists :
val (alice, bob) = (Person("Alice", 50), Person("Bob", 40))
val foo = new Foo[Person] {}
foo.baz(alice, bob)
// String = first is bigger
// using an explicit ordering
foor.baz(alice, bob)(Ordering.by[Person, String](_.name))
// String = first is smaller or equal
In the same manner as I compared Persons by age, you could create an Ordering[A] to compare your A by your quality function.
To complement Peter's answer: in Scala we have two traits: Ordering[T] and Ordered[A]. You should use them in different situations.
Ordered[A] is for cases when a class you implement can be ordered naturally and that order is the only one.
Example:
class Fraction(val numerator: Int, val denominator: Int) extends Ordered[Fraction]
{
def compare(that: Fraction) = {
(this.numerator * that.denominator) compare (this.denominator * that.numerator)
}
}
Ordering[T] is for cases when you want to have different ways to order things. This way the strategy of defining the order can be decoupled from the class being ordered.
For an example I will borrow Peter's Person:
case class Person(name: String, age: Int)
object PersonNameOrdering extends Ordering[Person]
{
def compare(x: Person, y: Person) = x.name compare y.name
}
Note, that since PersonNameOrdering doesn't have any instance fields, all it does is encapsulate the logic of defining an order of two Person's. Thus I made it an object rather than a class.
To cut down the boilerplate you can use Ordering.on to define an Ordering:
val personAgeOrdering: Ordering[Person] = Ordering.on[Person](_.age)
Now to the fun part: how to use all this stuff.
In your original code Foo[A].quantity was indirectly defining a way to order your A's. Now to make it idiomatic Scala let's use Ordering[A] instead, and rename quantity to ord:
trait Foo[A] {
def baz(x1: A, x2: A, ord: Ordering[A]) = {
import ord._
if (x1 > x2) "first is greater"
else "first is less or equal"
}
}
Several things to note here:
import ord._ allows to use infix notation for comparisons, i.e. x1 > x2 vs ord.gt(x1, x2)
baz is now parametrized by ordering, so you can dynamically choose how to order x1 and x2 on a case-by-case basis:
foo.baz(person1, person2, PersonNameOrdering)
foo.baz(person1, person2, personAgeOrdering)
The fact that ord is now an explicit parameter can sometimes be inconvenient: you may not want to pass it explicitly all the time, while there might be some cases when you want to do so. Implicits to the rescue!
def baz(x1: A, x2: A) = {
def inner(implicit ord: Ordering[A]) = {
import ord._
if (x1 > x2) "first is greater"
else "first is less or equal"
}
inner
}
Note the implicit keyword. It is used to tell the compiler to draw the parameter from the implicit scope in case you don't provide it explicitly:
// put an Int value to the implicit scope
implicit val myInt: Int = 5
def printAnInt(implicit x: Int) = { println(x) }
// explicitly pass the parameter
printAnInt(10) // would print "10"
// let the compiler infer the parameter from the implicit scope
printAnInt // would print "5"
You might want to learn where does Scala look for implicits.
Another thing to note is the need of a nested function. You cannot write def baz(x1: A, x2: A, implicit ord: Ordering[A]) - that would not compile, because the implicit keyword applies to the whole parameter list.
In order to cope with this little problem baz was rewritten in such a clunky way.
This form of rewritting turned out to be so common that a nice syntactic sugar was introduced for it - multiple parameter list:
def baz(x1: A, x2: A)(implicit ord: Ordering[A]) = {
import ord._
if (x1 > x2) "first is greater"
else "first is less or equal"
}
The need of an implicit parametrized by a type is also quite common so the code above can be rewritten with even more sugar - context bound:
def baz[A: Ordering](x1: A, x2: A) = {
val ord = implicitly[Ordering[A]]
import ord._
if (x1 > x2) "first is greater"
else "first is less or equal"
}
Please bear in mind that all these transformations of baz function are nothing but syntactic sugar application. So all the versions are exactly the same and compiler would desugarize each of the versions to the same bytecode.
To recap:
extract the A ordering logic from quantity function to the Ordering[A] class;
put an instance of Ordering[A] to the implicit scope or pass the ordering explicitly depending on your needs;
pick "your flavor" of syntactic sugar for baz: no sugar/nested functions, multiple parameter list or context bound.
UPD
To answer the original question "why doesn't it compile?" let me start from a little digression on how infix comparison operator works in Scala.
Given the following code:
val x: Int = 1
val y: Int = 2
val greater: Boolean = x > y
Here's what actually happens. Scala doesn't have infix operators per se, instead infix operators are just a syntactic sugar for single parameter method invocation. So internally the code above transforms to this:
val greater: Boolean = x.>(y)
Now the tricky part: Int doesn't have an > method on its own. Pick ordering by inheritance on the ScalaDoc page and check that this method is listed in a group titled "Inherited by implicit conversion intWrapper from Int to RichInt".
So internally compiler does this (well, except that for performance reasons that there is no actual instantiation of an extra object on heap):
val greater: Boolean = (new RichInt(x)).>(y)
If we proceed to ScalaDoc of RichInt and again order methods by inheritance it turns out that the > method actually comes from Ordered!
Let's rewrite the whole block to make it clearer what actually happens:
val x: Int = 1
val y: Int = 2
val richX: RichInt = new RichInt(x)
val xOrdered: Ordered[Int] = richX
val greater: Boolean = xOrdered.>(y)
The rewriting should have highlighted the types of variables involved in comparison: Ordered[Int] on the left and Int on the right. Refer > documentation for confirmation.
Now let's get back to the original code and rewrite it the same way to highlight the types:
trait Foo[A] {
def quality[B](x: A): Ordered[B]
def baz(x1: A, x2: A) = {
// some algorithm work here, and then
val x1Ordered: Ordered[B] = quality(x1)
val x2Ordered: Ordered[B] = quality(x2)
if (x1Ordered > x2Ordered) {
// some stuff
}
}
}
As you can see the types do not align: they are Ordered[B] and Ordered[B], while for > comparison to work they should have been Ordered[B] and B respectively.
The question is where do you get this B to put on the right? To me it seems that B is in fact the same as A in this context. Here's what I came up with:
trait Foo[A] {
def quality(x: A): Ordered[A]
def baz(x1: A, x2: A) = {
// some algorithm work here, and then
if (quality(x1) > x2) {
"x1 is greater"
} else {
"x1 is less or equal"
}
}
}
case class Cargo(weight: Int)
class CargoFooImpl extends Foo[Cargo] {
override def quality(x: Cargo): Ordered[Cargo] = new Ordered[Cargo] {
override def compare(that: Cargo): Int = x.weight compare that.weight
}
}
The downside of this approach is that it is not obvious: the implementation of quality is too verbose and quality(x1) > x2 is not symmetrical.
The bottom line:
if you want the code to be idiomatic Scala go for Ordering[T]
if you don't want to mess with implicits and other Scala magic implement quality as quality(x: A): Double for all As; Doubles are good and generic enough to be compared and ordered.
I can understand why the following code can't be compiled:
trait Hello[+A] {
def test[B<:A](x: B)
}
Because:
val child: Hello[String] = new Hello[String] {
def test[B <: String](x: B) = x.substring(1)
}
val parent: Hello[Any] = child
parent.test(123) // child.test can't handle integer
But I can't understand well why the following code can't be compiled:
trait Hello[+A] {
def test[B<:A]
}
The difference is the later one doesn't have parameters, we can't pass any value to the test method.
Why compiler still think it's invalid?
When you trying doing it in repl, it says:
scala> trait Hello[+A] {
| def test[B<:A](x: B)
| }
<console>:8: error: covariant type A occurs in contravariant position in type <: A of type B
def test[B<:A](x: B)
^
Rightly so. Imagine if this was possible and you could:
val x:Hello[Dog] = new Hello[Dog]{..}
val y:Hello[Animal] = x
y.test(Cat)//Oops
About the parameters, what makes you think it makes it safe without any arguments. You could get the variable using say implicitly and do dangerous stuff which compiler will not stop you. Example:
def test[B<:A]:B = this
I ran into some code that looks pretty much like this:
object SomeOddThing extends App {
val c: C = new C
val a: A = c
val b: B = c
// these will all print None
println(a.x)
println(b.x)
println(c.x)
}
abstract class A {
def x: Option[String] = None
}
abstract class B extends A {
override def x: Option[String] = Some("xyz")
}
class C extends B {
// x now has type None.type instead of Option[String]
override def x = None
}
trait T {
this: B =>
override def x = Some("ttt")
}
// this won't compile with the following error
// error: overriding method x in class C of type => None.type;
// method x in trait T of type => Some[String] has incompatible type
// class D extends C with T {}
// ^
class D extends C with T {}
This looks like a bug to me. Either the type of C.x should be inferred correctly or the class shouldn't compile at all.
The spec 4.6.4 only promises to infer a conforming type for the result type of the overriding method.
See https://issues.scala-lang.org/browse/SI-7212 and be thankful you didn't throw.
Maybe it will change:
https://groups.google.com/forum/#!topic/scala-internals/6vemF4hOA9A
Update:
Covariant result types are natural. It's not grotesque that it infers what it would normally do. And that you can't widen the type again. It's maybe suboptimal, as that other issue puts it. (Speaking to my comment that it's an improvement rather than a bug per se.)
My comment on the ML:
This falls under "always annotate interface methods, including
interface for extension by subclass."
There are lots of cases where using an inferred type for an API method commits you to a type you had rather avoided. This is also true for the interface you present to subclasses.
For this problem, we're asking the compiler to retain the last explicitly ascribed type, which is reasonable, unless it isn't. Maybe we mean don't infer singleton types, or Nothing, or something like that. /thinking-aloud
scala> trait A ; trait B extends A ; trait C extends B
defined trait A
defined trait B
defined trait C
scala> trait X { def f: A }
defined trait X
scala> trait Y extends X { def f: B }
defined trait Y
scala> trait Z extends Y { def f: C }
defined trait Z
scala> trait X { def f: A = new A {} }
defined trait X
scala> trait Y extends X { override def f: B = new B {} }
defined trait Y
scala> trait Z extends Y { override def f: C = new C {} }
defined trait Z
scala> trait ZZ extends Z { override def f: A = new C {} }
<console>:13: error: overriding method f in trait Z of type => C;
method f has incompatible type
trait ZZ extends Z { override def f: A = new C {} }
^
To the question, what does it mean for None.type to conform to Option?
scala> implicitly[None.type <:< Option[_]]
res0: <:<[None.type,Option[_]] = <function1>
to show that None.type, the singleton type of the None object, is in fact an Option.
Usually, one says that the compiler avoids inferring singleton types, even when you kind of want it to.
Programming in Scala says, "Usually such types are too specific to be useful."
Update: I modified the example so that can be compiled and tested.
I have an implicit class that defines an enrichment method:
case class Pipe[-I,+O,+R](f: I => (O, R));
object Pipe {
// The problematic implicit class:
implicit class PipeEnrich[I,O,R](val pipe: Pipe[I,O,R]) extends AnyVal {
def >->[X](that: Pipe[O,X,R]): Pipe[I,X,R] = Pipe.fuse(pipe, that);
def <-<[X](that: Pipe[X,I,R]): Pipe[X,O,R] = Pipe.fuse(that, pipe);
}
def fuse[I,O,X,R](i: Pipe[I,O,R], o: Pipe[O,X,R]): Pipe[I,X,R] = null;
// Example that works:
val p1: Pipe[Int,Int,String] = Pipe((x: Int) => (x, ""));
val q1: Pipe[Int,Int,String] = p1 >-> p1;
// Example that does not, just because R = Nothing:
val p2: Pipe[Int,Int,Nothing] = Pipe((x: Int) => (x, throw new Exception));
val q2: Pipe[Int,Int,String] = p2 >-> p2;
}
The problem is it doesn't work when R is Nothing in the second example. It results in an compiler error: In such a case, I get the following compiler error:
Pipe.scala:19: error: type mismatch;
found : Pipe[Int,Int,R]
required: Pipe[Int,Int,String]
val q2: Pipe[Int,Int,String] = p2 >-> p2;
Why does this happen?
I managed to solve it by creating a separate implicit class for that case:
trait Fuse[I,O,R] extends Any {
def >->[X](that: Pipe[O,X,R])(implicit finalizer: Finalizer): Pipe[I,X,R];
}
protected trait FuseImpl[I,O,R] extends Any with Fuse[I,O,R] {
def pipe: Pipe[I,O,R];
def >->[X](that: Pipe[O,X,R]) = Pipe.fuse(pipe, that);
def <-<[X](that: Pipe[X,I,R]) = Pipe.fuse(that, pipe);
}
implicit class PipeEnrich[I,O,R](val pipe: Pipe[I,O,R])
extends AnyVal with FuseImpl[I,O,R];
implicit class PipeEnrichNothing[I,O](val pipe: Pipe[I,O,Nothing])
extends AnyVal with FuseImpl[I,O,Nothing];
But can I rely on Scala's behavior in the future, that it will not consider Nothing as an option for R? If that changes in the future, the code will stop working because I'll have two different applicable implicits.
Well... You haven't shown all your code, and the code you did show has some confusing inconsistencies. So this is going to be a wild guess. I suspect your problem is that Pipe is invariant in its type parameter R. Here's my simplified example:
case class Test[A](a: A)
object Test {
implicit class TestOps[A](val lhs: Test[A]) extends AnyVal {
def >->(rhs: Test[A]): Test[A] = ???
}
def test {
def lhs = Test(???)
def rhs = Test(???)
lhs >-> rhs
}
}
The compile error I get from this code is:
value >-> is not a member of Test[Nothing]
lhs >-> rhs
^
... which I admit is not the same as the error you posted. But I don't entirely trust what you posted, so I'm going to keep going! The fix for this is to make Test covariant in its type parameter A:
case class Test[+A](a: A)
I honestly don't understand why the compile error happens to begin with. It seems like the compiler doesn't want to unify A =:= Nothing in the conversion to TestOps, but I don't see why not. Nevertheless, Test should be covariant in A anyways, and I'm guessing your Pipe class should likewise be covariant in R.
Edit
I just spent a few minutes looking through the Scala bug list and found several possibly related issues: SI-1570, SI-4509, SI-4982 and SI-5505. I don't really know any details, but it sounds like Nothing is treated specially and shouldn't be. Paul and Adriaan would be the guys to ask...
I don't seem to understand the Scala type system. I'm trying to implement
two base traits and a trait for a family of algorithms to work with them.
What am I doing wrong in the below?
The base traits for moves & states; these are simplified to just include
methods that expose the problem.
trait Move
trait State[M <: Move] {
def moves: List[M]
def successor(m: M): State[M]
}
Here's the trait for the family of algorithms that makes use of above.
I'm Not sure this is right!
There might be some +M / -S stuff involved...
trait Algorithm {
def bestMove[M <: Move, S <: State[M]](s: S): M
}
Concrete move and state:
case class MyMove(x: Int) extends Move
class MyState(val s: Map[MyMove,Int]) extends State[MyMove] {
def moves = MyMove(1) :: MyMove(2) :: Nil
def successor(p: MyMove) = new MyState(s.updated(p, 1))
}
I'm on very shaky ground regarding the below, but the compiler seems to accept it...
Attempting to make a concrete implementation of the Algorithm trait.
object MyAlgorithm extends Algorithm {
def bestMove(s: State[Move]) = s.moves.head
}
So far there are no compile errors; they show up when I try to put all the parts together, however:
object Main extends App {
val s = new MyState(Map())
val m = MyAlgorithm.bestMove(s)
println(m)
}
The above throws this error:
error: overloaded method value bestMove with alternatives:
(s: State[Move])Move <and>
[M <: Move, S <: State[M]](s: S)M
cannot be applied to (MyState)
val m = MyAlgorithm.bestMove(s)
^
Update: I changed the Algorithm trait to use abstract type members, as
suggested. This solved the question as I had phrased it but I had
simplified it a bit too much. The MyAlgorithm.bestMove() method must be
allowed to call itself with the output from s.successor(m), like this:
trait Algorithm {
type M <: Move
type S <: State[M]
def bestMove(s: S): M
}
trait MyAlgorithm extends Algorithm {
def score(s: S): Int = s.moves.size
def bestMove(s: S): M = {
val groups = s.moves.groupBy(m => score(s.successor(m)))
val max = groups.keys.max
groups(max).head
}
}
The above gives now 2 errors:
Foo.scala:38: error: type mismatch;
found : State[MyAlgorithm.this.M]
required: MyAlgorithm.this.S
val groups = s.moves.groupBy(m => score(s.successor(m)))
^
Foo.scala:39: error: diverging implicit expansion for type Ordering[B]
starting with method Tuple9 in object Ordering
val max = groups.keys.max
^
Do I have to move to an approach using traits of traits, aka the Cake pattern, to make this work? (I'm just guessing here; I'm thoroughly confused still.)
You declare MyAlgorithm#bestMove explicitly as taking a State[Move] parameter, but inside Main you are trying to pass it a MyState, which is a State[MyMove] not a State[Move].
You have a couple of options to resolve this. One would be to not constrain the types in MyAlgorithm:
object MyAlgorithm extends Algorithm {
def bestMove[M <: Move, S <: State[M]](s: S) : M = s.moves.head
}
Unfortunately, the scala type inference isn't smart enough to figure these types out for you, so at the call site, you have to declare them, making the call to MyAlgorithm#bestMove look like this:
val m = MyAlgorithm.bestMove[MyMove, MyState](s)
Another option use abstract type members of the Algorithm trait:
trait Algorithm {
type M <: Move
type S <: State[M]
def bestMove(s: S): M
}
And resolve the abstract types in the concrete implementation:
object MyAlgorithm extends Algorithm {
type M = MyMove
type S = MyState
def bestMove(s: S) : M = s.moves.head
}
Then the call site gets to return to your original version, without mentioning the types:
val m = MyAlgorithm.bestMove(s)
You may want to keep MyAlgorithm unaware of the actual types, and leave the determining of those types to the 'clients' of that object, in which case, change the object to a trait:
trait MyAlgorithm extends Algorithm {
def bestMove(s: S) : M = s.moves.head
}
Then in your Main class, you instantiate a MyAlgorithm with the concrete types:
val a = new MyAlgorithm {
type M = MyMove
type S = MyState
}
val m = a.bestMove(s)
Your comment "There might be some +M / -S stuff involved" was a good guess, but It won't work for you here. You might hope that the covariant type modifier "+" might help here. If you had declared the type parameter on State as
State[+M]
This would indicate that State[M] <:< State[N] if M <:< N. (read <:< as "is a subtype of"). Then you would have no problem passing in a State[MyMove] where a State[Move] was expected. However, you cannot use the covariant modifier on M here because it appears in the contravariant position as an argument to the successor function.
Why is this a problem? Your declaration of successor says that it will take an M and return a State. The covariant annotation says that a State[M] is also a State[Any]. So we should allow this assignment:
val x : State[Any] = y : State[MyMove]
Now if we have a State[Any], then x.successor is what type? Any => MyMove. Which cannot be correct, since your implementation is expecting a MyMove, not an Any
For updated code.
The compiler is very fair with complaints. Algorithm use one subclass of State as denoted and state successor may return any other subclass of State[M]
You may declare IntegerOne class
trait Abstract[T]
class IntegerOne extends Abstract[Int]
but the compiler have no clue that all instances of AbstractOne[Int] would be IntegerOne. It assume that there may be another class that also implements Abstract[Int]
class IntegerTwo extends Abstract[Int]
You may try to use implicit conversion to cast from Abstract[Int] to IntegerOne, but traits have no implicit view bounds as they have no value parameters at all.
Solution 0
So you may rewrite your Algorithm trait as an abstract class and use implicit conversion:
abstract class MyAlgorithm[MT <: Move, ST <: State[MT]] (implicit val toSM : State[MT] => ST) extends Algorithm {
override type M = MT // finalize types, no further subtyping allowed
override type S = ST // finalize types, no further subtyping allowed
def score(s : S) : Int = s.moves.size
override def bestMove(s : S) : M = {
val groups = s.moves.groupBy( m => score(toSM ( s.successor(m)) ) )
val max = groups.keys.max
groups(max).head
}
}
implicit def toMyState(state : State[MyMove]) : MyState = state.asInstanceOf[MyState]
object ConcreteAlgorithm extends MyAlgorithm[MyMove,MyState]
object Main extends App {
val s = new MyState(Map())
val m = ConcreteAlgorithm.bestMove(s)
println(m)
}
There are two drawbacks in this solution
using implicit conversion with asInstanceOf
tying types
You may extinguish first as the cost of further type tying.
Solution 1
Let use Algorithm as sole type parameterization source and rewrite type structure accordingly
trait State[A <: Algorithm] { _:A#S =>
def moves : List[A#M]
def successor(m : A#M): A#S
}
trait Algorithm{
type M <: Move
type S <: State[this.type]
def bestMove(s : S) : M
}
In that case your MyAlgorithm may be used without rewriting
trait MyAlgorithm extends Algorithm {
def score(s : S) : Int = s.moves.size
override def bestMove(s : S) : M = {
val groups = s.moves.groupBy(m => score(s.successor(m)))
val max = groups.keys.max
groups(max).head
}
}
Using it:
class MyState(val s : Map[MyMove,Int]) extends State[ConcreteAlgorithm.type] {
def moves = MyMove(1) :: MyMove(2) :: Nil
def successor(p : MyMove) = new MyState(s.updated(p,1))
}
object ConcreteAlgorithm extends MyAlgorithm {
override type M = MyMove
override type S = MyState
}
object Main extends App {
val s = new MyState(Map())
val m = ConcreteAlgorithm.bestMove(s)
println(m)
}
See more abstract and complicated usage example for this tecnique: Scala: Abstract types vs generics
Solution 2
There is also a simple solution to your question but I doubt it can solve your problem. You will eventually stuck upon type inconsistency once again in more complex use cases.
Just make MyState.successor return this.type instead of State[M]
trait State[M <: Move] {
def moves : List[M]
def successor(m : M): this.type
}
final class MyState(val s : Map[MyMove,Int]) extends State[MyMove] {
def moves = MyMove(1) :: MyMove(2) :: Nil
def successor(p : MyMove) = (new MyState(s.updated(p,1))).asInstanceOf[this.type]
}
other things are unchanged
trait Algorithm{
type M <: Move
type S <: State[M]
def bestMove(s : S) : M
}
trait MyAlgorithm extends Algorithm {
def score(s : S) : Int = s.moves.size
override def bestMove(s : S) : M = {
val groups = s.moves.groupBy(m => score(s.successor(m)))
val max = groups.keys.max
groups(max).head
}
}
object ConcreteAlgorithm extends MyAlgorithm {
override type M = MyMove
override type S = MyState
}
object Main extends App {
val s = new MyState(Map())
val m = ConcreteAlgorithm.bestMove(s)
println(m)
}
Pay attention to final modifier to MyState class. It ensures that conversion asInstanceOf[this.type] is correct one. Scala compiler may compute itself that final class keeps always this.type but it still have some flaws.
Solution 3
There is no need to tie Algorithm with custom State. As long as Algorithm does not use specific State function it may be written simpler without type bounding exercises.
trait Algorithm{
type M <: Move
def bestMove(s : State[M]) : M
}
trait MyAlgorithm extends Algorithm {
def score(s : State[M]) : Int = s.moves.size
override def bestMove(s : State[M]) : M = {
val groups = s.moves.groupBy(m => score(s.successor(m)))
val max = groups.keys.max
groups(max).head
}
}
This simple example doesn't come to my mind quickly because I've assumed that binding to different states are obligatory. But sometimes only part of system really should be parameterized explicitly and your may avoid additional complexity with it
Conclusion
Problem discussed reflects bunch of problems that arises in my practice very often.
There are two competing purposes that should not exclude each other but do so in scala.
extensibility
generality
First means that you can build complex system, implement some basic realization and be able to replace its parts one by one to implement more complex realization.
Second allows your to define very abstract system, that may be used for different cases.
Scala developers had very challenging task for creating type system for a language that can be both functional and object oriented while being limited to jvm implementation core with huge defects like type erasure. Co/Contra-variance type annotation given to users are insufficient for expressing types relations in complex system
I have my hard times every time I encounter extensiblity-generality dilemma deciding which trade-off to accept.
I'd like not to use design pattern but to declare it in the target language. I hopes that scala will give me this ability someday.