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
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.