Search code examples
kotlinsandbox

How to create list/set of functions in Kotlin


I have this code in java

// set of functions to transform int to String
private static final Set<IntFunction<String>> RULE_SET = new LinkedHashSet<IntFunction<String>>() {{
    add(i -> i % 2 == 0 ? "buzz" : "");
    add(i -> i % 3 == 0 ? "fizz" : "");
    add(i -> i % 4 == 0 ? "2gis" : "");
}};

//client code
private String transformNum(int num) {
    final String transformed = RULE_SET.stream()
            .map(rule -> rule.apply(num))
            .collect(Collectors.joining());
    return transformed.length() == 0 ? String.valueOf(num) : transformed;
}

and now I'm trying to transform it to Kotlin. But I feel that there is much simpler and easier way to create collection of functions, could you please advise? There is what I have now. Works, but looks weird for me, like I'm using Java in Kotlin, but not Kotlin itself. :)

private val rules = setOf<IntFunction<String>>(
        IntFunction { i: Int -> if (i % 2 == 0) "buzz" else "" },
        IntFunction { i: Int -> if (i % 3 == 0) "fizz" else "" },
        IntFunction { i: Int -> if (i % 4 == 0) "2gis" else "" }
)

private fun transformNum(num: Int): String {
    val transformed = rules.joinToString("") { rule: IntFunction<String> ->
        rule.apply(num)
    }
    return if (transformed.isEmpty()) num.toString() else transformed
}




Solution

  • maybe this?

    val ss = setOf<(Int) -> String>(
         { i -> if (i%2 == 0) "apple" else ""},
         { i -> if (i%3 == 0) "banana" else ""},
         { i -> if (i%4 == 0) "cherry" else ""}
     )
    
    private fun transform(num: Int): String = 
        ss.joinToString(""){ it(num) }
            .let {
                if (it.isEmpty()) num.toString() else it
            }