Is it possible to change visibility of sealed subclass for java interop?

Code:

    sealed class S {
           companion object {
               operator fun invoke(condition: Boolean): S {
                    return if(condition) A() else B()
               }
           }
    }
    private class A : S()
    private class B : S()

Problem:
Android library Fragments requires classes to be public static, but actually generated java classes A and B are not like that. Is it possible to specify required visiblity for them?

There’s no reason that A or B is private. If you want to make it pretty from Java you could use @JvmName to rename the invoke operator to be something like newInstance or create.

This is a sample, an actual condition is pretty complex and calculated inside of the invoke() factory method. private keyword is desirable to hide direct instantiation and from autocompletion. It works fine for basic classes, but android library Fragments checks if fragment subclass has a public constructor without parameters and can’t find it and crashes app

1 Like

well under the hood internal declarations are public synthetic declarations on the JVM, so maybe try declaring those subclasses as internal and see what happens.

You can change the visibility of the constructor only to internal and have the types public.

He said

though, and so most likely he doesn’t even want any outside caller to be aware that that declaration exists.