Erix
Erix

Reputation: 7105

Specifying inner class argument vs object

I'd like to accept an argument of an inner class type somewhere, but I'm not sure of how to do this, for example,

class Outer(...) {
  class Inner(...) { }
}

object Outer {...}

....

someFunc(arg : Outer.Inner) = {...}

but Scala is looking for type Inner in object Outer, not class Outer. so I get "type Inner is not a member of object Outer"

I'd like not to change the definitions of Outer/Inner if possible.

Upvotes: 0

Views: 49

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

If you want a path dependent type, you'll have to require an instance of type Outer to be provided, so you can refer to that instances Inner type as well:

someFunc(outer: Outer)(inner: outer.Inner) = {...}

That, or define an inner function where there is an Outer instance in scope.

If you just want an instance of Inner, unrelated to the Outer instance, then you're looking for type projection:

someFunc(inner: Outer#Inner) = {...}

It isn't too clear from your question which of the two you want.

Upvotes: 4

thwiegan
thwiegan

Reputation: 2173

Without knowing what exactly you want to achieve:

You need to have an instance of your Outer class in scope to access the type definition of your Inner type:

class Outer() {
  class Inner() { }
}

object Outer {

}

val o = new Outer()
def someFunc(arg : o.Inner) = {

}

someFunc(new o.Inner())

This is because in Scala inner classes are bound to the outer object and not to the enclosing class (see here)

Upvotes: 0

Related Questions