I always hated the implementation for .toString()
of Duration
. It gives you a string like that: PT8H6M12.345S
(not a hash)
Apparently, it’s an ISO 8601 thing, but what the hell am I supposed to do with that?
It’s not useful for outputting to end users (which is fair enough), but I don’t even want to write that into a log message.
I got so used to this just being garbage that I would automatically call .toMillis()
and write “ms” after it.
Well, and not to gush about Rust too much, but I recently learned that its debug string representation is actually really good. As in, it’s better than my Java workaround, because it’ll even do things like printing 1000ms as 1s.
And that’s just like, oh right, libraries can actually provide a better implementation than what I’ll slap down offhandedly.
Yep, some code examples from the official documentation. This:
printPersons( roster, (Person p) -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25 );
…is syntactic sugar for this:
interface CheckPerson { boolean test(Person p); } printPersons( roster, new CheckPerson() { public boolean test(Person p) { return p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25; } } );
…which is syntactic sugar for this:
interface CheckPerson { boolean test(Person p); } class CheckPersonEligibleForSelectiveService implements CheckPerson { public boolean test(Person p) { return p.gender == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25; } } printPersons(roster, new CheckPersonEligibleForSelectiveService());
The
printPersons
function looks like this:public static void printPersons(List<Person> roster, CheckPerson tester) { for (Person p : roster) { if (tester.test(p)) { p.printPerson(); } } }
Basically, if you accept a parameter that implements an interface with only one method (
CheckPerson
), then your caller can provide you an object like that by using the lambda syntax from the first example.They had to retrofit lambdas into the language, and they sure chose the one hammer that the language has.
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html