minizibi
minizibi

Reputation: 671

Kotlin's scopes - exposing single entry point

Hello I have a simple question about kotln's scopes. I always design my modules to get an single entry point for module. It's just one (exact one) public class. I really care for this kind of hermetization. So imagine these 2 classes (please pay attention for packages):

package group.moduleA.service
internal class HiddenService() {

    fun someFunction {

    }
}

  package group.moduleA.service
    class Service(private val hiddenService: HiddenService) {

        fun someFunction {

        }
    }

So we have 2 classes in same package, one is public and the second one internal. You can imagine there is a lot of internal classes there. I would like to make visible just only Service class to another modules. Pretty common (for me) behavior in Java. In kotlin I get an error:
"public function exposes its internal parameter..."
Am I doing something wrong or it's just how Kotlin scopes works? How can I solve this problem?

Upvotes: 0

Views: 156

Answers (2)

Rene
Rene

Reputation: 6148

You have to declare the constructor internal or private and provide another function / constructor to create your service:

class Service internal constructor(private val hiddenService: HiddenService) {
    constructor() : this(HiddenService())

    fun someFunction() {

    }
}

Upvotes: 1

Alexey Soshin
Alexey Soshin

Reputation: 17691

Dependency inversion principle is a good place to start:

internal class HiddenServiceImpl : HiddenService {
    override fun someFunction() {    
    }
}

interface HiddenService {
    fun someFunction()
}


class Service(private val hiddenService: HiddenService) {
    fun someFunction() {  
    }
}

Other option is to use factory method:

class Service private constructor(hiddenService: HiddenService) {

    companion object {
        fun create() = Service(HiddenService())
    }

    fun someFunction() {

    }
}

Upvotes: 0

Related Questions