0

I don't understand why when I build my project I have this error

Error:(118, 17) java: incompatible types: invalid method reference method isPresent in class java.util.Optional cannot be applied to given types required: no arguments found: com.siplec.matricee.adresse.model.AdresseVersion reason: actual and formal argument lists differ in length

My code :

var optionalAdresseVersion = adresseVersionRepository
    .findByIdVersionAndDeletedDateIsNull(idVersion);

var idAdresse = optionalAdresseVersion
    .filter(Optional::isPresent)
    .map(Optional::get);

Method - findByIdVersionAndDeletedDateIsNull

I use the interface JpaRepository

@Repository
public interface AdresseVersionRepository extends JpaRepository<AdresseVersion, AdresseVersionFk> {

Optional<AdresseVersion> findByIdVersionAndDeletedDateIsNull(String idVersion);
}

Object - AdresseVersion

@IdClass(value = AdresseVersionFk.class)
@Data
@Builder
@Entity
@Table(name = "ADRESSE_VERSION")
@ToString
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = {"idAdresse", "idVersion"})
public class AdresseVersion extends AbstractAuditingEntity {

  @Id
  @Column(name = "ADRESSE_FK")
  private String idAdresse;

  @Id
  @Column(name = "ID_ADRESSE_VERSION")
  private String idVersion;

  @Column(name = "DELETED_DATE")
  private ZonedDateTime deletedDate;
}

Also I don't understand the error message from IntelliJ IDEA when I tried to used my Object Optional :

"Non-static method cannot be referenced from a static context"

Community
  • 1
  • 1
Theo Dury
  • 141
  • 2
  • 9
  • 1
    You can't call an instance method from a static method or block, plain and simple. You likely need to check if any methods called in those contexts are instance-based. – Austin Schaefer Jul 26 '19 at 09:54

2 Answers2

2

You get this error because the method filter() takes a predicate that is applicable to the type contained inside the optional, not on the optional itself.

To fix the problem:

It depends what you want to get in idAdresse when it's not present. Here I'll assume you want to leave it null:

var idAdresse = optionalAdresseVersion
    .map(AdresseVersion::getIdAdresse)
    .orElse(null);
Benoit
  • 5,118
  • 2
  • 24
  • 43
2

optionalAdresseVersion's type is Optional<AdresseVersion>, filter parameter type is Predicate<? super AdresseVersion>

var idAdresse = optionalAdresseVersion
    .map(AdresseVersion::getIdAdresse).orElse(null);
Ivan Young
  • 329
  • 2
  • 6