Why don't Scanner methods return void?

Viewed 59

I've noticed that when using scanners, if I want to set attributes such as delimiter or locale, the methods to do so return the Scanner object itself:

public Scanner useDelimiter(String pattern) {
    modCount++;
    delimPattern = patternCache.forName(pattern);
    return this;
}

What I don't understand is that, if the attribute is changed (instead of it creating a new object), why does it return a Scanner object instead of void? It's not like I have to store the return value inside a variable - in fact, if I try to do so, like in the code below, Eclipse will give the message Resource leak: 'lineScanner' is not closed at this location:

Scanner scanner = new Scanner(new File("accounts.csv"));
String line;
    
while(scanner.hasNextLine()) {
    line = scanner.nextLine();
    Scanner lineScanner = new Scanner(line);
    lineScanner = lineScanner.useDelimiter(",");
    ...
}
1 Answers

This is more for convenience than anything else. The return value can be ignored; it just allows you to chain methods for readability.

E.g.

lineScanner.useDelimiter(",").useLocale(Locale.US).useRadix(10);

This is more readable and shorter than

lineScanner.useDelimiter(",");
lineScanner.useLocale(Locale.US);
lineScanner.useRadix(10);
Related