PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to instantiate inner classes in one step in Scala?

 July 08, 2022     class, inner-classes, java, scala, syntax     No comments   

Issue

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?


Solution

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()


Answered By - 0__
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing