@Getter to return Optional if value is nullable

4,565 views
Skip to first unread message

Itamar Benjamin

unread,
Jan 29, 2018, 2:24:37 PM1/29/18
to Project Lombok
Hi,
I'm not sure if this feature is implemented, but i didn't find it in the documentation so thought i'd ask here.

I was thinking it will be nice that @Getter annotation, when generating a getter for a field, will set the return value of the getter to be Optional<T> (when T is the field's type of course) if this field can hold null values(if it was marked with @Nullable, or in the contrary if it wasn't marked with @NonNull).
This should obviously work only for non-primitive fields that can actually be nulled.


Do you know if there's support for this or something similar? what do you think of the idea?


Thanks,
Itamar.

Reinier Zwitserloot

unread,
Mar 18, 2018, 10:14:06 AM3/18/18
to Project Lombok
Returning Optional for getters is not advised by just about all the pros, us first amongst them (both Roel and I think Optional makes far harder to read, less flexible, worse code, and using Optional anywhere outside of its intended use, which is as the returned value for stream operations, will result in more time spent hunting down bugs).

Given the above, don't keep your hopes up that we're going to add Optional support to lombok, well, _ever_.

Gerard Bosch

unread,
Jan 22, 2019, 7:35:36 AM1/22/19
to Project Lombok
Hi Reinier,

I find the approach of Stephen Colebourne (a Java pro as you mention) very convenient:

So why not implement it in Lombok as something optional that users can decide to use or not? The default @Getter could be as always was, but why not a @Getter(optional = true) setting to alleviate users to write their own getters for nullable fields when necessary?

I'm sure there are several Lombok users desiring this feature:

The point is, Lombok is mainly used to reduce boilerplate and forcing users to write their own getters for the use cases they want to wrap a field into an Optional is tedious. From the usage standpoint, using Lombok and writing custom getters to just wrap into optional is a little cumbersome.

Thanks,
Gerard

P.S. I know the Optional usage is a very controversial matter, but really makes sense in many cases for a getter as Stephen Colebourne shows in his post.


El diumenge, 18 març de 2018 15:14:06 UTC+1, Reinier Zwitserloot va escriure:

Reinier Zwitserloot

unread,
Jan 22, 2019, 7:41:12 AM1/22/19
to Project Lombok
We (especially I) are more or less famous for strongly advocating you don't use optional, at all, anywhere, with possibly the one exception being as part of a stream terminal operation.

Stephen and I will just have to agree to disagree on this one.
Reply all
Reply to author
Forward
0 new messages