返回内部类调用对象函数

时间:2017-12-04 11:34:03

标签: android object architecture kotlin internal

我正在使用Kotlin进行测试,我正在编写一个小型库,供测试App项目导入和使用。

在库项目中,我将我的课程标记为internal,因为我不希望它们对于App项目是可见的,但是我想为该库提供一个入口点,并且我正在使用如下所示的Kotlin object

LIBRARY

object Library {
   fun getComponent() = AwesomeComponent()
}

internal class AwesomeComponent() {
   // some implementation
}


TEST APP

class MainActivity : AppCompatActivity() {

   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      val component = Library.getComponent()
   }
} 

问题是这不能编译,因为库object中的函数返回internal类型,因此也需要标记为内部,但这样做会隐藏来自TestApp的功能。

另一种选择是根本没有internal修饰符,以便TestApp可以看到Library方法,但是它也可以看到Library项目中的类

我是否在这里忽略了一个简单的解决方案,还是需要重新规划图书馆项目的包和结构? (在这种情况下不确定该怎么做)

1 个答案:

答案 0 :(得分:3)

您必须为app模块发布某种公共API才能使用getComponent()方法返回的组件。如果要发布有关库的最小信息,可以让它返回一个仅包含对库的公共方法调用的接口,并使您的类实现该接口:

object Library {
    fun getComponent(): IAwesomeComponent = AwesomeComponent()
}

interface IAwesomeComponent {
     // methods you want to call on the component in the app module
}

internal class AwesomeComponent(): IAwesomeComponent {
    // implementations of the interface methods
}
相关问题