Skip to content
Advertisement

void with Generics in Java

I have a function that returns void

public interface IProductService {
   void delete(String id);
}

Generic method

public interface IRequestHandler<C , R> {
    R handler(C c);
    Class<C> commandType();
}

Implementation of generic interface

 @Singleton
    public record DeleteProductCommandHandler(IProductService iProductService)
            implements IRequestHandler<DeleteProductCommand, Void> {


        @Override
        public Void handler(DeleteProductCommand deleteProductCommand) {
            return iProductService.delete(deleteProductCommand.id);
        }

        @Override
        public Class<DeleteProductCommand> commandType() {
            return DeleteProductCommand.class;
        }
    }

How can I use void in IRequestHandler<DeleteProductCommand, Void> so that I can map void from iProductService.delete(deleteProductCommand.id);

Advertisement

Answer

Option 1:

Just return null:

@Override
public Void handler(DeleteProductCommand deleteProductCommand) {
    iProductService.delete(deleteProductCommand.id);
    return null;
}

Option 2:

Update the IProductService::delete method to return something meaningful, e.g. a boolean value like Collection::remove does:

public interface IProductService {
   boolean delete(String id);
}
@Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
            implements IRequestHandler<DeleteProductCommand, Boolean> {

    @Override
    public Boolean handler(DeleteProductCommand deleteProductCommand) {
        return iProductService.delete(deleteProductCommand.id);
    }

    @Override
    public Class<DeleteProductCommand> commandType() {
        return DeleteProductCommand.class;
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement