Java interop - accessing inner classes

93 views
Skip to first unread message

Paul Butcher

unread,
Mar 12, 2011, 5:33:55 AM3/12/11
to scala-user
I can't help but think that I'm being dumb, but I just can't work out how to access an inner class implemented in Java :-(

Given the following Java:

> public class Foo {
> public class Bar {
> Bar() {}
> }
>
> public Bar getBar() { return new Bar(); }
> }


I get:

> scala> val f = new Foo
> f: Foo = Foo@756a7c99
>
> scala> val b = new Foo.Bar
> <console>:5: error: type Bar is not a member of object Foo
> val b = new Foo.Bar
> ^
>
> scala> val b = f.getBar
> b: Foo#Bar = Foo$Bar@3cecfaea
>
> scala> val b2 = new Foo#Bar
> <console>:5: error: Foo is not a legal prefix for a constructor
> val b2 = new Foo#Bar
> ^


What am I missing?

(note that I'm aware of the "Scala can't access a static inner class" issue. But this isn't a static inner class).

--
paul.butcher->msgCount++

Snetterton, Castle Combe, Cadwell Park...
Who says I have a one track mind?

http://www.paulbutcher.com/
LinkedIn: http://www.linkedin.com/in/paulbutcher
MSN: pa...@paulbutcher.com
AIM: paulrabutcher
Skype: paulrabutcher

Nate Nystrom

unread,
Mar 12, 2011, 5:44:14 AM3/12/11
to Paul Butcher, scala-user
scala> val f = new Foo
f: Foo = Foo@3ee969f8

scala> new f.Bar
res1: f.Bar = Foo$Bar@53e36ec6

Foo#Bar is a supertype of f.Bar, but it's not a class, so you can't instantiate it. I had to make the Bar constructor public to avoid an IllegalAccessError.

Nate

thomas rimmele

unread,
Mar 12, 2011, 5:45:34 AM3/12/11
to scala-user
This is not a scala problem. Pure Java:


public class Foo {
    public class Bar {
        Bar() {
        }
    }

    public Bar getBar() {
        return new Bar();
    }
   
    public static void main(String[] args) {
        System.out.println(new Foo().getBar());
        System.out.println(new Bar()); // ERROR
    }
}


To say it with the words of eclipse:
   No enclosing instance of type Foo is accessible. Must qualify the allocation with an enclosing instance of type Foo (e.g. x.new A() where x is an instance of Foo).

Greetings, Thomas

Paul Butcher

unread,
Mar 12, 2011, 5:46:15 AM3/12/11
to Nate Nystrom, scala-user
On 12 Mar 2011, at 10:44, Nate Nystrom wrote:
> Foo#Bar is a supertype of f.Bar, but it's not a class, so you can't instantiate it. I had to make the Bar constructor public to avoid an IllegalAccessError.

D'oh! I knew I was being dumb. Thanks!

Reply all
Reply to author
Forward
0 new messages