1

I want to validate multiple fields of a Person and return a Validated object with all related errors. I use kotlin version 1.3.41 and arrow 0.8.2.

I have the following classes:

class Person(id: Long, name: String)

sealed class PersonError {
    data class InvalidId(val field: String) : PersonError()
    data class InvalidName(val field: String) : PersonError()
}

So, when I do my validation, I want the following result type back:

 Validated<List<PersonError>, Person>

The arrow library documentation was not really a help, as I am new to functional programming. The example in the video does not compile with the latest arrow version, it expects a semigroup:

    Validated.applicative<PersonError>(**SEMIGROUP**).map(vId, vName, { id, name
        Person(id, name)
    }).ev()

Another use, the implementation of Emmanuel Nhan, does also not compile with the latest kotlin version: https://github.com/enhan/validation-case/blob/master/src/main/kotlin/eu/enhan/validation/kotlin/sample.kt

ielkhalloufi
  • 652
  • 1
  • 10
  • 27

1 Answers1

1

The solution is from Emmauel Nhan, read his blog: https://www.enhan.eu/how-to-in-fp/

ValidatedNel.applicative<Nel<PersonError>>(Nel.semigroup<PersonError>())
        .map(id, name){
            val id = it.a
            val name = it.b
            Person(id, name)
        }.fix()

Above results to: Validated<Nel<PersonError>, Person>

ielkhalloufi
  • 652
  • 1
  • 10
  • 27