001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.functor.adapter; 018 019import org.apache.commons.functor.Function; 020import org.apache.commons.functor.Procedure; 021import org.apache.commons.lang3.Validate; 022 023/** 024 * Adapts a 025 * {@link Procedure Procedure} 026 * to the 027 * {@link Function Function} interface 028 * by always returning <code>null</code>. 029 * 030 * @param <A> the argument type. 031 * @param <T> the returned value type. 032 * @version $Revision: 1537906 $ $Date: 2013-11-01 12:47:33 +0100 (Fr, 01 Nov 2013) $ 033 */ 034public final class ProcedureFunction<A, T> implements Function<A, T> { 035 /** The {@link Procedure Procedure} I'm wrapping. */ 036 private final Procedure<? super A> procedure; 037 038 /** 039 * Create a new ProcedureFunction. 040 * @param procedure to adapt 041 */ 042 public ProcedureFunction(Procedure<? super A> procedure) { 043 this.procedure = Validate.notNull(procedure, "Procedure argument was null"); 044 } 045 046 /** 047 * {@inheritDoc} 048 */ 049 public T evaluate(A obj) { 050 procedure.run(obj); 051 return null; 052 } 053 054 /** 055 * {@inheritDoc} 056 */ 057 @Override 058 public boolean equals(Object obj) { 059 if (obj == this) { 060 return true; 061 } 062 if (!(obj instanceof ProcedureFunction<?, ?>)) { 063 return false; 064 } 065 ProcedureFunction<?, ?> that = (ProcedureFunction<?, ?>) obj; 066 return this.procedure.equals(that.procedure); 067 } 068 069 /** 070 * {@inheritDoc} 071 */ 072 @Override 073 public int hashCode() { 074 int hash = "ProcedureFunction".hashCode(); 075 hash ^= procedure.hashCode(); 076 return hash; 077 } 078 079 /** 080 * {@inheritDoc} 081 */ 082 @Override 083 public String toString() { 084 return "ProcedureFunction<" + procedure + ">"; 085 } 086 087 /** 088 * Adapt a Procedure to the Function interface. 089 * @param <A> the argument type. 090 * @param <T> the returned value type. 091 * @param procedure to adapt 092 * @return ProcedureFunction 093 */ 094 public static <A, T> ProcedureFunction<A, T> adapt(Procedure<? super A> procedure) { 095 return null == procedure ? null : new ProcedureFunction<A, T>(procedure); 096 } 097 098}