class Unit:
def __init__(self, symbol):
self.s, self.a = symbol, []
def cond(self, x, y):
self.a.append((x, 'f' + repr(y)))
def parse(self, x):
for a, b in self.a:
if a(x): return eval(b)
else: return f'{x} {self.s}'
x = Unit('files')
x.cond(lambda x: not x, '0 files')
x.cond(lambda x: x == 1, '1 file')
x.cond(lambda x: x > 999, '{x:,} files')
s = x.parse(a)
This routine can be used to parse a unit-system as well, e.g., 'B', 'kB', 'MB', etc.
class Unit {
String s;
interface F<T> { T f(int x); }
record G(F x, F y) {}
List<G> m = new ArrayList<>();
Unit(String symbol) { s = symbol; }
void cond(F x, F y) {
m.add(new G(x, y));
}
String parse(int x) {
for (G g : m)
if ((boolean) g.x.f(x))
return (String) g.y.f(x);
return x + (' ' + s);
}
}
Unit u = new Unit("files");
u.cond(x -> x == 1, x -> "1 file");
String s = u.parse(a);