简体   繁体   中英

How to instantiate inner classes in one step in Scala?

Consider this code:

class Outer {
  class Inner
}

In Java it would be possible to create an instance of Inner with:

Outer.Inner inner = new Outer().new Inner();

I know I can write this in Scala:

val outer = new Outer
val inner = new outer.Inner

But I wonder if it is possible to express the same without the assignment to outer .

Both

new Outer.new Inner  

and

new (new Outer).Inner

are not accepted by the compiler.

Is there something I'm missing?

First of all, I doubt that the instantiation in one go is any meaningful -- you are like throwing away the Outer instance, keeping no reference to it. Makes me wonder, if you weren't thinking of a Java static inner class, like

public class Outer() {
   public static class Inner() {}
}

which in Scala would translate to Inner being an inner class of Outer 's companion object:

object Outer {
    class Inner
}

new Outer.Inner

If you really want an inner dependent class, and you just want more convenient syntax for instantiating it, you could add a companion object for it :

class Outer {
   object Inner {
      def apply() = new Inner()
   }
   class Inner
}

new Outer().Inner()

If you have class declared like this:

class Outer {
  class Inner
}

then you need to instantiate outer class first and then instantiate inner class as following:

val outerTest = new Outer()
val innerTest = new outerTest.Inner()

now you can call inner class methods from using innerTest variable.

This worked for me

it("Instantiate inner java class in scala") {
  val outer: Outer = new Outer()
  val inner = new outer.Inner("","")

}
(new Outer() { def apply() = new Inner()})()

或者

(new Outer() { val inner = new Inner()}).conditionObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM