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

com.github.tonivade.purefun.Tuple2 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 java.io.Serializable;
import java.util.Objects;

import com.github.tonivade.purefun.data.Sequence;

@HigherKind
public final class Tuple2 implements Tuple, Serializable {

  private static final long serialVersionUID = 5034828839532504174L;

  private static final Equal> EQUAL = Equal.>of()
      .comparing(Tuple2::get1)
      .comparing(Tuple2::get2);

  private final A value1;
  private final B value2;

  private Tuple2(A value1, B value2) {
    this.value1 = value1;
    this.value2 = value2;
  }

  public A get1() {
    return value1;
  }

  public B get2() {
    return value2;
  }

  @Override
  public Sequence toSequence() {
    return Sequence.listOf(value1, value2);
  }

  public  Tuple2 map1(Function1 mapper) {
    return map(mapper, Function1.identity());
  }

  public  Tuple2 map2(Function1 mapper) {
    return map(Function1.identity(), mapper);
  }

  public  Tuple2 map(Function1 mapper1, Function1 mapper2) {
    return Tuple2.of(mapper1.apply(value1), mapper2.apply(value2));
  }

  public static  Tuple2 of(A value1, B value2) {
    return new Tuple2<>(value1, value2);
  }

  public  R applyTo(Function2 function) {
    return function.apply(value1, value2);
  }

  @Override
  public int hashCode() {
    return Objects.hash(value1, value2);
  }

  @Override
  public boolean equals(Object obj) {
    return EQUAL.applyTo(this, obj);
  }

  @Override
  public String toString() {
    return "Tuple2(" + value1 + ", " + value2 + ")";
  }
}