Home > Enterprise >  How to make concrete implementation of an interface not accessible outside the scope of the library.
How to make concrete implementation of an interface not accessible outside the scope of the library.

Time:05-19

I'm working on developing an Android library. I want to make a few classes inaccessible to the users who implement my library. Mostly the interface realization classes. For instance, I have the following classes in moduleA,

  • Animal ( interface )
  • Dog ( Realization of Animal interface )
  • AnimalProvider ( Object that helps to initialize Animal object from the activity/any view )

Since I'm using Kotlin I made Dog an internal class to make it inaccessible outside the library scope. But, the problem is AnimalProvider is an object that has a public function called getAnimalSource(). Something like this,

object AnimalProvider {
 fun getAnimalSource(
 context: Context, 
 lifecycleOwner: LifecycleOwner
 ) = Dog( context = Context, lifecycleOwner = lifecycleOwner)

And it's throwing an error like,

public function exposes its internal return type.

I need this function to initialize the Animal object from the activity/view. Am I approaching the issue in the right direction.? Or, what's the proper way to hide concrete classes when you publish an android library.?

CodePudding user response:

The problem with your code is that it implicitly declares the return type of getAnimalSource() to be Dog, and Dog is internal.

You need to hide that type, by explicitly declaring the return type of getAnimalSource():

object AnimalProvider {
 fun getAnimalSource(
 context: Context, 
 lifecycleOwner: LifecycleOwner
 ): Animal = Dog( context = Context, lifecycleOwner = lifecycleOwner)

Now, getAnimalSource() is declared to return an Animal, not a Dog, and you should be in better shape.

  • Related