Is there any reason to use the safe-navigation operator on constructor?

80 Views Asked by At

A friend of mine have sent me the following code:

def pass = new File("password_file.txt")?.text ?: "pass"

Is there any reason to use the ?. operator after a constructor? As far as I understand it, the constructor can either return a new object or throw an exception, therefore there can never be a null.

1

There are 1 best solutions below

2
On

Your understanding is correct. There is no need to be null safe invoking text in your example. The elvis operator should probably still be used in case the file is empty.