Home | History | Annotate | Download | only in base
      1 /*
      2  * Copyright (C) 2007 The Guava Authors
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.base;
     18 
     19 import static com.google.common.base.Preconditions.checkArgument;
     20 import static com.google.common.base.Preconditions.checkNotNull;
     21 
     22 import com.google.common.annotations.Beta;
     23 import com.google.common.annotations.GwtCompatible;
     24 
     25 import java.io.Serializable;
     26 import java.util.Map;
     27 
     28 import javax.annotation.Nullable;
     29 
     30 /**
     31  * Static utility methods pertaining to {@code Function} instances.
     32  *
     33  * <p>All methods return serializable functions as long as they're given serializable parameters.
     34  *
     35  * <p>See the Guava User Guide article on <a href=
     36  * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
     37  * Function}</a>.
     38  *
     39  * @author Mike Bostock
     40  * @author Jared Levy
     41  * @since 2.0 (imported from Google Collections Library)
     42  */
     43 @GwtCompatible
     44 public final class Functions {
     45   private Functions() {}
     46 
     47   /**
     48    * Returns a function that calls {@code toString()} on its argument. The function does not accept
     49    * nulls; it will throw a {@link NullPointerException} when applied to {@code null}.
     50    *
     51    * <p><b>Warning:</b> The returned function may not be <i>consistent with equals</i> (as
     52    * documented at {@link Function#apply}). For example, this function yields different results for
     53    * the two equal instances {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}.
     54    */
     55   public static Function<Object, String> toStringFunction() {
     56     return ToStringFunction.INSTANCE;
     57   }
     58 
     59   // enum singleton pattern
     60   private enum ToStringFunction implements Function<Object, String> {
     61     INSTANCE;
     62 
     63     @Override
     64     public String apply(Object o) {
     65       checkNotNull(o);  // eager for GWT.
     66       return o.toString();
     67     }
     68 
     69     @Override public String toString() {
     70       return "toString";
     71     }
     72   }
     73 
     74   /**
     75    * Returns the identity function.
     76    */
     77   // implementation is "fully variant"; E has become a "pass-through" type
     78   @SuppressWarnings("unchecked")
     79   public static <E> Function<E, E> identity() {
     80     return (Function<E, E>) IdentityFunction.INSTANCE;
     81   }
     82 
     83   // enum singleton pattern
     84   private enum IdentityFunction implements Function<Object, Object> {
     85     INSTANCE;
     86 
     87     @Override
     88     @Nullable
     89     public Object apply(@Nullable Object o) {
     90       return o;
     91     }
     92 
     93     @Override public String toString() {
     94       return "identity";
     95     }
     96   }
     97 
     98   /**
     99    * Returns a function which performs a map lookup. The returned function throws an {@link
    100    * IllegalArgumentException} if given a key that does not exist in the map. See also {@link
    101    * #forMap(Map, Object)}, which returns a default value in this case.
    102    *
    103    * <p>Note: if {@code map} is a {@link com.google.common.collect.BiMap BiMap} (or can be one), you
    104    * can use {@link com.google.common.collect.Maps#asConverter Maps.asConverter} instead to get a
    105    * function that also supports reverse conversion.
    106    */
    107   public static <K, V> Function<K, V> forMap(Map<K, V> map) {
    108     return new FunctionForMapNoDefault<K, V>(map);
    109   }
    110 
    111   private static class FunctionForMapNoDefault<K, V> implements Function<K, V>, Serializable {
    112     final Map<K, V> map;
    113 
    114     FunctionForMapNoDefault(Map<K, V> map) {
    115       this.map = checkNotNull(map);
    116     }
    117 
    118     @Override
    119     public V apply(@Nullable K key) {
    120       V result = map.get(key);
    121       checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key);
    122       return result;
    123     }
    124 
    125     @Override public boolean equals(@Nullable Object o) {
    126       if (o instanceof FunctionForMapNoDefault) {
    127         FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
    128         return map.equals(that.map);
    129       }
    130       return false;
    131     }
    132 
    133     @Override public int hashCode() {
    134       return map.hashCode();
    135     }
    136 
    137     @Override public String toString() {
    138       return "forMap(" + map + ")";
    139     }
    140 
    141     private static final long serialVersionUID = 0;
    142   }
    143 
    144   /**
    145    * Returns a function which performs a map lookup with a default value. The function created by
    146    * this method returns {@code defaultValue} for all inputs that do not belong to the map's key
    147    * set. See also {@link #forMap(Map)}, which throws an exception in this case.
    148    *
    149    * @param map source map that determines the function behavior
    150    * @param defaultValue the value to return for inputs that aren't map keys
    151    * @return function that returns {@code map.get(a)} when {@code a} is a key, or {@code
    152    *         defaultValue} otherwise
    153    */
    154   public static <K, V> Function<K, V> forMap(Map<K, ? extends V> map, @Nullable V defaultValue) {
    155     return new ForMapWithDefault<K, V>(map, defaultValue);
    156   }
    157 
    158   private static class ForMapWithDefault<K, V> implements Function<K, V>, Serializable {
    159     final Map<K, ? extends V> map;
    160     final V defaultValue;
    161 
    162     ForMapWithDefault(Map<K, ? extends V> map, @Nullable V defaultValue) {
    163       this.map = checkNotNull(map);
    164       this.defaultValue = defaultValue;
    165     }
    166 
    167     @Override
    168     public V apply(@Nullable K key) {
    169       V result = map.get(key);
    170       return (result != null || map.containsKey(key)) ? result : defaultValue;
    171     }
    172 
    173     @Override public boolean equals(@Nullable Object o) {
    174       if (o instanceof ForMapWithDefault) {
    175         ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
    176         return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue);
    177       }
    178       return false;
    179     }
    180 
    181     @Override public int hashCode() {
    182       return Objects.hashCode(map, defaultValue);
    183     }
    184 
    185     @Override public String toString() {
    186       return "forMap(" + map + ", defaultValue=" + defaultValue + ")";
    187     }
    188 
    189     private static final long serialVersionUID = 0;
    190   }
    191 
    192   /**
    193    * Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition
    194    * is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}.
    195    *
    196    * @param g the second function to apply
    197    * @param f the first function to apply
    198    * @return the composition of {@code f} and {@code g}
    199    * @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a>
    200    */
    201   public static <A, B, C> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) {
    202     return new FunctionComposition<A, B, C>(g, f);
    203   }
    204 
    205   private static class FunctionComposition<A, B, C> implements Function<A, C>, Serializable {
    206     private final Function<B, C> g;
    207     private final Function<A, ? extends B> f;
    208 
    209     public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) {
    210       this.g = checkNotNull(g);
    211       this.f = checkNotNull(f);
    212     }
    213 
    214     @Override
    215     public C apply(@Nullable A a) {
    216       return g.apply(f.apply(a));
    217     }
    218 
    219     @Override public boolean equals(@Nullable Object obj) {
    220       if (obj instanceof FunctionComposition) {
    221         FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
    222         return f.equals(that.f) && g.equals(that.g);
    223       }
    224       return false;
    225     }
    226 
    227     @Override public int hashCode() {
    228       return f.hashCode() ^ g.hashCode();
    229     }
    230 
    231     @Override public String toString() {
    232       return g + "(" + f + ")";
    233     }
    234 
    235     private static final long serialVersionUID = 0;
    236   }
    237 
    238   /**
    239    * Creates a function that returns the same boolean output as the given predicate for all inputs.
    240    *
    241    * <p>The returned function is <i>consistent with equals</i> (as documented at {@link
    242    * Function#apply}) if and only if {@code predicate} is itself consistent with equals.
    243    */
    244   public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
    245     return new PredicateFunction<T>(predicate);
    246   }
    247 
    248   /** @see Functions#forPredicate */
    249   private static class PredicateFunction<T> implements Function<T, Boolean>, Serializable {
    250     private final Predicate<T> predicate;
    251 
    252     private PredicateFunction(Predicate<T> predicate) {
    253       this.predicate = checkNotNull(predicate);
    254     }
    255 
    256     @Override
    257     public Boolean apply(@Nullable T t) {
    258       return predicate.apply(t);
    259     }
    260 
    261     @Override public boolean equals(@Nullable Object obj) {
    262       if (obj instanceof PredicateFunction) {
    263         PredicateFunction<?> that = (PredicateFunction<?>) obj;
    264         return predicate.equals(that.predicate);
    265       }
    266       return false;
    267     }
    268 
    269     @Override public int hashCode() {
    270       return predicate.hashCode();
    271     }
    272 
    273     @Override public String toString() {
    274       return "forPredicate(" + predicate + ")";
    275     }
    276 
    277     private static final long serialVersionUID = 0;
    278   }
    279 
    280   /**
    281    * Creates a function that returns {@code value} for any input.
    282    *
    283    * @param value the constant value for the function to return
    284    * @return a function that always returns {@code value}
    285    */
    286   public static <E> Function<Object, E> constant(@Nullable E value) {
    287     return new ConstantFunction<E>(value);
    288   }
    289 
    290   private static class ConstantFunction<E> implements Function<Object, E>, Serializable {
    291     private final E value;
    292 
    293     public ConstantFunction(@Nullable E value) {
    294       this.value = value;
    295     }
    296 
    297     @Override
    298     public E apply(@Nullable Object from) {
    299       return value;
    300     }
    301 
    302     @Override public boolean equals(@Nullable Object obj) {
    303       if (obj instanceof ConstantFunction) {
    304         ConstantFunction<?> that = (ConstantFunction<?>) obj;
    305         return Objects.equal(value, that.value);
    306       }
    307       return false;
    308     }
    309 
    310     @Override public int hashCode() {
    311       return (value == null) ? 0 : value.hashCode();
    312     }
    313 
    314     @Override public String toString() {
    315       return "constant(" + value + ")";
    316     }
    317 
    318     private static final long serialVersionUID = 0;
    319   }
    320 
    321   /**
    322    * Returns a function that always returns the result of invoking {@link Supplier#get} on {@code
    323    * supplier}, regardless of its input.
    324    *
    325    * @since 10.0
    326    */
    327   @Beta
    328   public static <T> Function<Object, T> forSupplier(Supplier<T> supplier) {
    329     return new SupplierFunction<T>(supplier);
    330   }
    331 
    332   /** @see Functions#forSupplier*/
    333   private static class SupplierFunction<T> implements Function<Object, T>, Serializable {
    334 
    335     private final Supplier<T> supplier;
    336 
    337     private SupplierFunction(Supplier<T> supplier) {
    338       this.supplier = checkNotNull(supplier);
    339     }
    340 
    341     @Override public T apply(@Nullable Object input) {
    342       return supplier.get();
    343     }
    344 
    345     @Override public boolean equals(@Nullable Object obj) {
    346       if (obj instanceof SupplierFunction) {
    347         SupplierFunction<?> that = (SupplierFunction<?>) obj;
    348         return this.supplier.equals(that.supplier);
    349       }
    350       return false;
    351     }
    352 
    353     @Override public int hashCode() {
    354       return supplier.hashCode();
    355     }
    356 
    357     @Override public String toString() {
    358       return "forSupplier(" + supplier + ")";
    359     }
    360 
    361     private static final long serialVersionUID = 0;
    362   }
    363 }
    364