Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why don't Scanner methods return void?

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(",");
    ...
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading