https://kotlinlang.org logo
#compiler
Title
# compiler
e

eygraber

02/14/2023, 6:25 PM
Is there a way to have a union of
protected
and
internal
visibility? Pretty sure the answer is no, but just checking. Are there any proposals for adding something like that? Use case is where I want to invoke an abstract function from a class in the same module, and have subclasses implement them.
a

Adam S

02/14/2023, 6:32 PM
the current closest equivalent is a custom OptIn annotation https://kotlinlang.org/docs/opt-in-requirements.html#require-opt-in-for-api then at least any usage needs to be explicit hmmm actually, maybe that’s not suitable for your use case
e

ephemient

02/14/2023, 6:42 PM
Copy code
abstract class Foo {
    abstract protected fun foo()

    companion object {
        internal fun Foo.foo() = foo()
    }
}
Copy code
import Foo.Companion.foo
super ugly, but assuming this is what you mean by "union"… this will allow
internal
, non-derived callers to use the extension
Foo.foo
, while derived callers use can use the
protected foo
.
e

eygraber

02/14/2023, 6:52 PM
mind blown
y

Youssef Shoaib [MOD]

02/15/2023, 10:19 AM
You could even do:
Copy code
abstract class Foo {
  abstract protected fun foo()
  final internal fun foo(unit: Unit = Unit) = this.foo()
}
(Haven't tested it out but I think it should work) it's slightly neater in that no import is required at the call site, but the unit parameter (which is needed for disambiguation) is annoying.
6 Views