Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

benefit in using operator invoke in functional interfaces

Tags:

kotlin

I am just wondering what is the benefit of using the operator invoke than not using it. I am trying it out on one of my interfaces to see what the benefits are.

fun interface MapperDomainToData<in E, out M> {
    operator fun invoke(entity: E): M
}

fun interface MapperDomainToData<in E, out M> {
    fun map(entity: E): M
}

In my implementation there seems to be no difference. In fact I prefer not using it as the method name is more meaningful.

class MapSocialLoginRequestImp @Inject constructor() : MapperDomainToData<SocialLoginRequestEntity, SocialLoginRequestModel> {
    override fun invoke(entity: SocialLoginRequestEntity): SocialLoginRequestModel {
        return SocialLoginRequestModel(
            token = entity.token,
            provider = entity.provider
        )
    }

    override fun map(entity: SocialLoginRequestEntity): SocialLoginRequestModel {
        return SocialLoginRequestModel(
            token = entity.token,
            provider = entity.provider
        )
    }
}

I think the second implementation is the more clear as the map method is more readable.

like image 879
ant2009 Avatar asked Feb 13 '26 11:02

ant2009


1 Answers

The difference isn't in how you declare the interface implementation, but only in how you use the interface object. Of course there's no difference in your code.

The difference is between

myMapper(entity)

and

myMapper.map(entity)

To be clear, it's entirely reasonable to prefer the second one, but that's the difference that the invoke operator function provides.

like image 193
Louis Wasserman Avatar answered Feb 15 '26 12:02

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!