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

net.sf.javagimmicks.transform8.BidiFunction Maven / Gradle / Ivy

There is a newer version: 0.99-alpha1
Show newest version
package net.sf.javagimmicks.transform8;

import java.util.function.Function;

/**
 * A bidirectional version of {@link Function} that is able to transform objects
 * back into their original value and/or format.
 * 
 * @param 
 *           the "from" or source type
 * @param 
 *           the "to" or target type
 */
public interface BidiFunction extends Function
{
   /**
    * Transforms a give (transformed object) back into the source value and/or
    * format.
    * 
    * @param source
    *           the source object to be transformed back
    * @return the back-transformed object
    */
   public F applyReverse(T source);

   /**
    * Returns a new {@link BidiFunction} that transforms in exactly the
    * different directions.
    * 
    * @return an inverted version of this {@link BidiFunction}
    */
   default BidiFunction invert()
   {
      return new BidiFunction()
      {
         @Override
         public T applyReverse(final F source)
         {
            return BidiFunction.this.apply(source);
         }

         @Override
         public F apply(final T source)
         {
            return BidiFunction.this.applyReverse(source);
         }

         @Override
         public BidiFunction invert()
         {
            return BidiFunction.this;
         }
      };
   }

   /**
    * Creates a new {@link BidiFunction} from two given {@link Function}s (which
    * should perform contrary operations).
    * 
    * @param forwardFunction
    *           the "forward" {@link Function}
    * @param backwardFunction
    *           the "backward" {@link Function} which should perform the
    *           contrary operation to the "forward" one
    * @param 
    *           the "from" or source type
    * @param 
    *           the "to" or target type
    * @return a resulting {@link BidiFunction}
    */
   static  BidiFunction of(final Function forwardFunction, final Function backwardFunction)
   {
      return new BidiFunction()
      {
         @Override
         public T apply(final F source)
         {
            return forwardFunction.apply(source);
         }

         @Override
         public F applyReverse(final T source)
         {
            return backwardFunction.apply(source);
         }
      };
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy