Kotlin android expose a class of one module in another?

Viewed 44

the setup:

Module 1 an external dependency that has Class A
Module 2 depends on Class A but may in the future depends on another module/class entirely
an APP depends on Module 2

I tried to add a typealias in Module 2 to Class A. it exposes the class "correctly" (lets say it is com.moduleTwo.ClassA instead of com.moduleOne.ClassA) but it makes it so that APP also needs to have a dependency on Module 1 or it doesn't compile with: Cannot access class 'com.moduleOne.ClassA'. Check your module classpath for missing or conflicting dependencies

How can one make Module 2 expose an alias to Class A without adding Module 1 to APP build.gradle? Is there a way to "inject" the dependency to APP?

1 Answers

If I understood correctly you would like to replace a module without having app's code depending on external libraries.

When your app's code depends on only the abstraction and not concrete implementation you can replace those dependencies at any time.

The piece of code below shows that User in app module depends on interface A but the real implementation of A may vary.

// library module A
interface A {
  fun doWork()
}
    
// library module B implements modules A & External
class B(private val external : External) : A {
    override fun doWork() {
    val result = external.getExternalStuff()
    // more work with result
  }
}

object Factory {
  fun createB(params...): B {
    val external = External(paramX)
    // ...
    return B(external)
  }
}
        
// library module C implements module A
class C : A {
  override fun doWork() {
      println("C works")
  }
}

// app 
// User knows only 'A'
class User(private val a: A) {
    fun help() {
      a.doWork()
  }
}
    
// Version 1: App implements modules A & B      
// app module will know nothing about External 
// but some factory or builder class to create B
fun appStarts() {
  val a = Factory.createB(params...)
  val user = User(a)
  user.help() 
}   
        
// Version 2: App implements modules A & C      
fun appStarts() {
  val a = C()
  val user = User(a)
  user.help() 
}   

Hope this helps.

Related