简体   繁体   中英

benefit in using operator invoke in functional interfaces

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM