Hello friendly Kotliners! I have an interface with...
# announcements
a
Hello friendly Kotliners! I have an interface with a fun that returns some custom related datatype:
Copy code
package somePkg

interface MyInterface {
  fun myFun(): MyType
  data class MyType
}
I don't want to pollute
somePkg
with
MyType
, since it's pretty specific to the domain of
MyInterface
, and there is other stuff in the same package. Are there any pitfalls to defining a data class inside an interface that I should be aware of? What about putting it inside companion object inside the interface? Is the only difference in the import statement you have to use?
d
For interfaces, yes. For classes, the nested class can access private members of it's containing class.
k
Really? I remember there being some difference between Java and Kotlin here, in that that wasn't allowed in Kotlin.
inner
classes can access private members though.
a
I also think
inner
keyword is required to access private members (ref. https://kotlinlang.org/docs/reference/nested-classes.html) However that's beside the question I'm asking 😛
a
Sorry, didn't spot the
private
part of your statement 🙂 You are right
k
Huh I remember being frustrated about something like this, dammit.
d
The reverse doesn't work though (outer access to private property of nested).
a
But this is still unrelated to whether defining data classes / types inside interface is reasonable or not, and whether they should exist directly in the interface, or within a companion object 😬
d
Personally I think it makes sense. Putting them in the companion object is a bit weird imho
However if you simply don't want to clutter the file system, you can put multiple top level types in one
.kt
file, too.
a
That'st the plan, however i didn't want to clutter the "root" namespace
a
I think it makes perfect sense to put it in the interface if it will only be used through the interface.
a
👍