2

I'm trying the following with Scala 2.10.0-M1:

trait Container {
  type X
}

class Test[C <: Container](val c: C) {
  def foo(x: c.X): C#X = x // this compiles fine
  def bar(x: C#X): c.X = x // this does not compile
}

The problem is the same when using this form:

def bar[C <: Container](c: C)(x: C#X): c.X = x

I don't really see why foo compiles while bar does not.

I believe that c.X and C#X should be the same here.

Also, I don't understand the error message:

[error]  found   : x.type (with underlying type C#X)
[error]  required: Test.this.c.X
[error]  possible cause: missing arguments for method or constructor
[error]   def bar(x: C#X): c.X = x // this does not compile

Any idea?

betehess
  • 817
  • 4
  • 18
  • That was actually a design issue, where I wanted to retrieve the type from a path-dependent type. I have created [another question](http://stackoverflow.com/questions/9065343/exposing-a-path-dependent-type-coming-from-a-singleton-type) for that. – betehess Jan 30 '12 at 14:29

3 Answers3

7

C#X means an X from any C. c.X means an X from your particular C, namely c. The latter is much more specific!

For example, if X is a bill and c is a particular customer, c.X means that the method only accepts bills from (for, presumably) customer c. C#X means it accepts any bill from any customer. If you want to ensure that customers only get charged with their own bills (at least by default), the former is what you want.

Rex Kerr
  • 162,454
  • 26
  • 308
  • 402
3

@Rex has given a good explanation of what's wrong. Here's how you might fix it ...

If it's reasonable to be able to return x as a result of type c.X (ie. a value of the X type of the particular c passed as an argument, then you can tighten it's type as an argument,

def bar[C <: Container](c: C)(x: c.X): c.X = x

Now bar will only accept values of type X which are relative to the specific value c. If that doesn't work for you at the call sites of bar, then you will need to rework your design.

Miles Sabin
  • 22,786
  • 6
  • 58
  • 95
2

c.X and C#X are definitely not the same -- if they were, why would both exist?

Consider the case where you have a and b, different instances of C. By definition, a.X and b.X are different, but both are C#X.

Daniel C. Sobral
  • 284,820
  • 82
  • 479
  • 670