How can I initialize a const member with a pure function?

54 Views Asked by At

How can I call a function when defining constants?

I have a complicated mechanism to generate names for an external system and would like to hide that complexity in a function, which I can then reuse in a bunch of places where I need to exchange data with that external service, so that I don't have to remember the details each time.

In Java I could do this:

public class Mcve {
    static final String FOO = magic("friendly name");

    private static String magic(String plain) {
        return plain.replaceAll(" ", "_");
    }

    public static void main(String... args) {
        System.out.println(FOO);
    }
}

This prints "friendly_name", as expected.

How do I do the same in Kotlin?

class Mcve {
    companion object {
        const val FOO = magic("friendly name")  // Const 'val' initializer should be a constant value

        fun magic(name: String): String {
            return name.replace(' ' , '_')
        }
    }
}

fun main() {
    println(Mcve.FOO)
}

In Kotlin, the compiler complains that

Const 'val' initializer should be a constant value

I've tried adding @JvmStatic to magic, but that did not change the error.

How can I use a (pure) function to initialize a const?

0

There are 0 best solutions below