Manuel Leduc
Manuel Leduc

Reputation: 1919

Scala in depth - Existential types

I am currently reading Scala in depth and I struggle with a point about existential types.

Using those sources : https://github.com/jsuereth/scala-in-depth-source/blob/master/chapter6/existential-types/existential.scala

with openjdk 7 and scala 2.10.3

The following instructions gives me a error :

val x = new VariableStore[Int](12)
val d = new Dependencies {}
val t = x.observe(println)
d.addHandle(t)

<console>:14: error: method addHandle in trait Dependencies cannot be accessed in types.Dependencies
 Access to protected method addHandle not permitted because
 enclosing object $iw is not a subclass of 
 trait Dependencies in package types where target is defined
              d.addHandle(t)
                ^

And I can't find out why and how I arrive to this error.

Edit 1 : I added the following code from Kihyo's answer :

class MyDependencies extends Dependencies {
  override def addHandle(handle: Ref) = super.addHandle(handle)
}

val x = new VariableStore[Int](12)
val d = new MyDependencies
val t = x.observe(println)
d.addHandle(t) //compiles

It make addHandle public instead of protected.

Now I have the following error message :

type mismatch; found : x.Handle (which expands to) x.HandleClass required: d.Ref (which 
 expands to) x.Handle forSome { val x: sid.types.obs.Observable }

HandleClass is a Handle and Ref is a Handle of any Observer (if I get it right) so the value t should be accepted as a correct type for the exception.

Upvotes: 0

Views: 163

Answers (1)

Kigyo
Kigyo

Reputation: 5768

In the trait Dependencies, addHandle is defined like that:

protected def addHandle(handle : Ref) : Unit

protected means, only subclasses can access this method and thats why you get the error. (which basically tells you exactly that)

Your code could work when you create a subclass that makes addHandle public:

class MyDependencies extends Dependencies {
  override def addHandle(handle: Ref) = super.addHandle(handle)
}

val x = new VariableStore[Int](12)
val d = new MyDependencies
val t = x.observe(println)
d.addHandle(t) //compiles

But I have no idea about that example and what you want to do with it.

@Edit1:

I get the same error as you, but I can't explain why. It worked for me when I extend App instead of having a main-method:

object TestObs extends App {
  val x = new VariableStore[Int](12)
  val d = new MyDependencies
  val t = x.observe(println)
  d.addHandle(t)
}  

Maybe someone else has some insight on this.

Upvotes: 1

Related Questions