All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.tonivade.purefun.Equal Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2020, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun;

import static java.util.Objects.isNull;
import static java.util.Objects.requireNonNull;

/**
 * This is a utility class to generate more readable {@code equals()} methods. It's based on {@link Eq} instances and it can combine
 * some of them to generate a bigger function that verify the equivalence between two instances of the same type {@code T}.
 *
 * 
  {@literal @Override}
 * public boolean equals(Object obj) {
 *   return{@literal }of()
 *     .comparing(Data::getId)
 *     .comparing(Data::getValue)
 *     .applyTo(this, obj);
 * }
* @param type to which it applies */ public final class Equal { private final Eq tester; private Equal(Eq tester) { this.tester = requireNonNull(tester); } public Equal append(Eq other) { return new Equal<>(tester.and(other)); } public Equal comparing(Function1 getter) { return append(Eq.comparing(getter)); } public Equal comparingArray(Function1 getter) { return append(Eq.comparingArray(getter)); } @SuppressWarnings("unchecked") public boolean applyTo(T self, Object obj) { requireNonNull(self); if (isNull(obj)) { return false; } if (sameObjects(self, obj)) { return true; } return sameClasses(self, obj) && areEquals(self, (T) obj); } private boolean areEquals(T self, T other) { return tester.eqv(self, other); } private boolean sameClasses(T self, Object obj) { return self.getClass() == obj.getClass(); } private boolean sameObjects(T self, Object obj) { return self == obj; } public static Equal of() { return new Equal<>(Eq.always()); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy