Arrow lens won't let me set a nullable property to null

376 views Asked by At

Given this (extremely simplified) code :

@optics
data class MigrationStatus(val token: String?)

val m = MigrationStatus(null)

I can call

val m1 = MigrationStatus.token.modify(m) { "some token" }

But as the argument type is a non nullable String, how can I modify token back to null ? Of course

val m2 = MigrationStatus.token.modify(m1) { null }

does not compile.

The same happens when changing token type to an Option<String> when trying to set it to None, but I avoided it as it is now deprecated (which I'm not sure I like, but that's another matter).

Did I miss something obvious ?

1

There are 1 answers

0
nomisRev On BEST ANSWER

The @Optics compiler generates 2 optics for that property.

MigrationStatus.token & MigrationStatus.tokenNullable or MigrationStatus.tokenOption in the case of Option.

This is because there are two different Optics that are useful here.

  • Lens which has set & get and in this case `Lens<MigrationStatus, String?>
  • Optional which has set & getOption and in this case `Optional<MigrationStatus, String>

The first one is the one you'd want to use in this case to be able to set String? to null.

So MigrationStatus.tokenNullable.set(null).

The latter is more useful for the DSL, and composition of Optics since if instead of String? you had another data class or sealed class you'd want to operate on the value only in the case of not-null.

I hope that fully answers your question!