# Optional.ofNullable should not be used on a primitive type

**URL:** <https://community.sonarsource.com/t/optional-ofnullable-should-not-be-used-on-a-primitive-type/37937>\
**Category:** New rules / language support\
**Tags:** java\
**Created:** [February 2, 2021, 6:42pm UTC](https://community.sonarsource.com/t/optional-ofnullable-should-not-be-used-on-a-primitive-type/37937 "2021-02-02T18:42:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![TomVanWemmel](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/tomvanwemmel/32/18886_2.png) [@TomVanWemmel](https://community.sonarsource.com/u/TomVanWemmel)\
**Post date:** [February 2, 2021, 6:42pm UTC](https://community.sonarsource.com/t/optional-ofnullable-should-not-be-used-on-a-primitive-type/37937/1 "2021-02-02T18:42:32Z")

</div>

Optional.ofNullable should only be used with non-null arguments. As primitive types can not hold a null-value, it makes sense to use Optional.of instead.  
The rule should validate that the argument is not a primitive type or a method returning a primitive type.

Noncompliant Code Example  
`Optional.ofNullable(getaLong()).ifPresent(System.out::println);`

Compliant Solution  
`Optional.of(getaLong()).ifPresent(System.out::println);`

---

<div class="post-metadata">

**Author:** ![Nicolas\_Harraudeau](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/nicolas_harraudeau/32/255_2.png) [@Nicolas\_Harraudeau](https://community.sonarsource.com/u/Nicolas_Harraudeau)\
**Post date:** [February 4, 2021, 8:47am UTC](https://community.sonarsource.com/t/optional-ofnullable-should-not-be-used-on-a-primitive-type/37937/2 "2021-02-04T08:47:47Z")

</div>

Hi @TomVanWemmel and Welcome to the community !

Also thank you for taking the time to suggest this rule. 🙂  
As said on Twitter, it makes complete sense to me. I’ll specify it and copy the link in this thread so that you can have a look.

Cheers,  
Nicolas
