Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Double Colon vs. Lambda in similarish Class

Tags:

kotlin

I understand my first second example uses a lambda function with a single parameter passed in. I'm trying to understand why it would be different from my second boilerplate example where a double colon is used instead of a lambda. (still a kotlin newb trying to wrap my head around double colons coming from a python background)

class Service(services: PluginServiceHub) {
    init {
        services.registerFlowInitiator(Landlord::class.java) { Landlord(it) }
    }
}

VS

class Service(services: PluginServiceHub) {
    init {
        services.registerFlowInitiator(IssuanceRequester::class.java, ::Issuer)
    }
}

What does the ::Issuer represent exactly?

like image 614
mleafer Avatar asked Jan 03 '23 16:01

mleafer


1 Answers

Assuming there is a class Issuer, ::Issuer will be a function reference to its constructor. A constructor taking the appropriate number of arguments (one in this case) will be resolved and used, which is equivalent to a lambda { Issuer(it) }.

If there's no such a class, a function named Issuer and taking one argument will be used, if it exists.

See: Are there constructor references in Kotlin?

like image 111
hotkey Avatar answered Jan 08 '23 05:01

hotkey