I want to create custom type that acts like Integer
or Double
. Lest say I have multilevel navigable map:
// [UserLevel: [UserBalance: Multiplier]]
NavigableMap<Integer, NavigableMap<Double, Double>> multiplierByBalanceAndLevel
It's absolutely not readable, if you don't look into the comment. And also always when I work with such Map
I should go to the declaration and check comment. It's absolutely annoying, and I want something like:
NavigableMap<UserLevel, NavigableMap<UserBalance, Multiplier>> multiplierByBalanceAndLevel
For example in scala it's possible to use:
type UserLevel = Int
Does it possible to implement in java somehow? Maybe there are some libraries for such purposes?
PS I can write custom implementation with lombok help
import java.util.NavigableMap;
import com.google.common.collect.ImmutableSortedMap;
import lombok.Value;
import lombok.experimental.Delegate;
public class TestExample {
@Value
static class UserLevel extends Number implements Comparable<UserLevel> {
@Delegate
Integer userLevel;
public int compareTo(UserLevel another) {
return this.userLevel.compareTo(another.getUserLevel());
}
}
@Value
static class UserBalance extends Number implements Comparable<UserBalance> {
@Delegate
Double userBalance;
public int compareTo(UserBalance another) {
return this.userBalance.compareTo(another.getUserBalance());
}
}
@Value
static class Multiplier extends Number implements Comparable<Multiplier> {
@Delegate
Double multiplier;
public int compareTo(Multiplier another) {
return this.multiplier.compareTo(another.getMultiplier());
}
}
public static void main(String[] args) {
double originalAmount = 10;
NavigableMap<UserLevel, NavigableMap<UserBalance, Multiplier>> multiplierByBalanceAndLevel =
ImmutableSortedMap.of(new UserLevel(1),
ImmutableSortedMap.of(new UserBalance(2.0), new Multiplier(3.0)));
Multiplier multiplier = multiplierByBalanceAndLevel
.floorEntry(new UserLevel(13)).getValue()
.ceilingEntry(new UserBalance(1.8)).getValue();
double amount = originalAmount * multiplier.getMultiplier();
}
}
But the use of wrapped classes looks ugly and produces a lot of boilerplate code, because they don't act like auto-boxed ones
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.