What’s the best way to map a String to a wrapper type in Scala, where optionality is inferred from the target type? #754
-
The context: I need to map a String to a wrapper type. The source comes from Proto3, where the optional keyword isn't used—so whether a field is optional or required is inferred from the target type. I've written a minimal script that reproduces this behavior, but I'm wondering: is there a cleaner or more idiomatic way to achieve this?
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I'm afraid not: most of the time I've met the requirement that validation for errors and optionality are orthogonal concepts:
Here it's contextual mixing of the two:
It might be perfectly reasonable in a particular case, but it screams "extraordinary" and it has to be handled as such. In the past any "silent failures" in Chimney were reported as bugs by the community, so I believe the current approach (where one needs to define such exceptional behavior explicitly) is still desired. At best you could use something like implicit def relaxedTransformer[A, B](implicit pt: PartialTransformer[A, B]): Transformer[A, Option[B]] =
(a: A) => pt.transformFailFast(a).asOption to generate such relaxed transformation for every import io.scalaland.chimney.partial.syntax._ // import once and then
implicit val stringToWrapper: PartialTransformer[String, Wrapper] =
PartialTransformer(src => Wrapper.from(src).asResult) // .asResult is available |
Beta Was this translation helpful? Give feedback.
-
It’s not really an error, just an absence of value — represented as an empty string in Protobuf. That’s why I’m asking, since this seems like a fairly common scenario. |
Beta Was this translation helpful? Give feedback.
I'm afraid not: most of the time I've met the requirement that validation for errors and optionality are orthogonal concepts:
None
Here it's contextual mixing of the two:
It might be perfectly reasonable in a particular case, but it screams "extraordinary" and it has to be handled as such. In the past any "silent failures" in Chimney were reported as bugs by the community, so I believe the current approach (where one needs to defin…