0

I have a Java class which I'm working with in Scala. I can instantiate the class, but I don't see how to instantiate a public static class within the outer class from Scala. Can anyone point me to the answer?

(I've read lots of posts that say how to use "static" members in Scala code. That is not what I'm looking for.)

1
  • There's no such thing as a "static inner class" in Java, by definition: "The static keyword may modify the declaration of a member type C within the body of a non-inner class or interface T. Its effect is to declare that C is not an inner class." and "An inner class is a nested class that is not explicitly or implicitly declared static." From the JLS. Commented Feb 19, 2017 at 4:11

1 Answer 1

0

In my case something like that works:

  • Java class

    package test.java;
    
    public class Test {
      public static class TestInner {}
    }
    
  • Scala class

    package test.scala
    
    import test.java.Test
    
    object Main {
    
      def main(args: Array[String]): Unit = {
        new Test.TestInner()
      }
    }
    
Sign up to request clarification or add additional context in comments.

5 Comments

That's the same as how you reference static nested classes in Java. However, it is a mistake to name the static nested class TestInner because that falsely implies to maintainers that the class is an inner class.
On language/JVM-level there might not be things like "inner static class", but conceptually static create namespace of sort - as such TestInner is inner to the namespace created by Test (though it can be accessed from outside of it). I guess that's what author meant and wanted to access.
When working with Java, it is best to use the terminology that applies to Java. "On [the] language level" is important when it's the language you're talking about.
But here we are talking about Scala language which do not have any notion of static in the first place, and so the person asking the question should not be forced to read the Java specification just for asking question and understanding solution.
Wasn't the example with TestInner declared labeled "Java class"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.