Functional Programming with kotlin - avoiding var

Viewed 163

I am working with kotlin and functional programming to develop an api.I really could not figure out whether did i break any FP rules here by using here. I have a following function which gives me customerNumber and bunch of other fields.

data class CustomerInfo(val customerNumber:String?=null,val accountNumber:String?=null,val email:String?=null)

and I have function with lot of conditions but conditions are same for all fields

fun getCustomerInfo(someDto:SomeDto,someOtherDto:SomeOtherDto,oneMoreDto:OneMoreDto):CustomerInfo
{
    var customerNumber = someDto.id
    var accountNo = someDto.accountNumber
    var email = someDto.email
    
    if(someCondition())
    { 
        customerNumber=   someOtherDto.id
        accountNo = someOtherDto.accountNo
        email = someOtherDto.email
    }else if(someOtherConditiion)
    {
        customerNumber=   oneMoreDto.id
        accountNo = oneMoreDto.accountNo
        email = oneMoreDto.email
    }
    //and many more conditions like this 
    return CustomerInfo(customerNumber,accountNo,email)
}

Is using var inside a functions is wrong?How can write this function without using var's here ? I know i can return the dto every-time directly once the condition met,but i feel like using same dto in 10 conditions?Any help would be appreciated

1 Answers

There is nothing technically wrong in using var, because you are in a local scope of a function.

But you could avoid lots of boilerplate code like:

fun getCustomerInfo(someDto:SomeDto,someOtherDto:SomeOtherDto,oneMoreDto:OneMoreDto):CustomerInfo
{
  return when {
    someCondition() -> CustomerInfo(someOtherDto.id, someOtherDto.accountNumber, someOtherDto.email)
    someOtherConditiion() -> CustomerInfo(oneMoreDto.id, oneMoreDto.accountNumber, oneMoreDto.email)
    else -> CustomerInfo(someDto.id, someDto.accountNumber, someDto.email)
  }
}

If all your (different) DTO's gets generated you could consider creating mapper extension functions for all of them:

// top-level functions
fun SomeDto.toConsumerInfo(): CustomerInfo = ConsumerInfor(id, accountNumber, email)
fun SomeOtherDto.toConsumerInfo(): CustomerInfo = ConsumerInfor(id, accountNumber, email)
fun OneMoreDto.toConsumerInfo(): CustomerInfo = ConsumerInfor(id, accountNumber, email)
// and more for other DTO's you want to map

Then you could use them like:

fun getCustomerInfo(someDto:SomeDto,someOtherDto:SomeOtherDto,oneMoreDto:OneMoreDto):CustomerInfo {
  return when {
    someCondition() -> someOtherDto.toConsumerInfo()
    someOtherConditiion() -> oneMoreDto.toConsumerInfo()
    else -> someDto.toConsumerInfo()
  }
Related