Why this Consumer complaining compile time error?

77 Views Asked by At

I am new to java8 and I am trying to write template method design pattern ,and I am using Consumer for this purpose but I donn't know where I am doing wrong.

    package org.java.series.ds.cleancode;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.function.Consumer;

public class Sample1 {
    public static void main(String[] args) throws Exception {
        OrderExporter exporter=new OrderExporter();
        Exporter exporter2=new Exporter();      
        exporter2.exportFiles("abc.csv", exporter::writeToCSV);

    }   

}

 class Exporter{    
    public  File exportFiles(String fileName,Consumer<Writer> consumer)throws Exception {
        File file=new File(fileName);
        try(FileWriter fileWriter=new FileWriter(file)){
            //writeContent(fileWriter);
            consumer.accept(fileWriter);
            return file;
        }catch (Exception e) {
            System.err.println(e);
            throw e;
        }
    }
}

class OrderExporter{
    public void writeToCSV(FileWriter fileWriter) throws IOException {
        fileWriter.write(String.format("%s,%d,%s", "kishan",29,"vns"));
    }
}

Any help would be appreciable.

1

There are 1 best solutions below

3
Andy Turner On

You can't use a method expecting a FileWriter as a Consumer<Writer> because such a consumer needs to accept any kind of Writer, but this method only accepts FileWriter or subclasses.

Since you are consuming a FileWriter inside the method, the trivial answer is to use that as the bound:

Consumer<FileWriter>

You can make it slightly more general using a lower bound:

Consumer<? super FileWriter>