how do I declare a static val in Kotlin?
# getting-started
y
how do I declare a static val in Kotlin?
v
Copy code
class Foo {
    companion object {
        const val BAR = "bar" // Const for primitives
        val someData = SomeData.default
    }
}
Everything inside an
object
is the equivalent to
static
in other languages. Kotlin also supports top-level definitions, so you don't need to define inside a class:
Copy code
const val BAR = "bar"

class Foo {
    fun doSomething() {
        println("BAR = $BAR")
    }
}
More about it: • Companion objectsObjects
y
so is it not possible to declare a local static? for example, a Regex object in a frequently-invoked closure.
nope 1
thanks, appreciated.
v
You can do something like:
Copy code
class Parser {
    
    fun isInputValid(input: String): Boolean {
        return REGEX_PATTERN.containsMatchIn(input)
    }
    
    private companion object {
        val REGEX_PATTERN = """[0-9]+""".toRegex()
    }
    
}
In order to avoid instantiating the Regex multiple times
y
I see. that’s what I expected. hoped there was a less boilerplatey way to do this.
again - thanks. you guys are really helpful
(this is a general comment about the replies here, heh)
l
If you want less boilerplate, you can do
Copy code
class Parser {
    
    fun isInputValid(input: String): Boolean {
        return REGEX_PATTERN.containsMatchIn(input)
    }
}

private val REGEX_PATTERN = """[0-9]+""".toRegex()
4
This makes REGEX_PATTERN a global variable that is scoped to the file.
k
I see that the language designers have gone to some lengths to explicitly prohibit creating companion objects inside a local class.
s
if you want even less code, you can do
Copy code
class Parser {
    
    fun isInputValid(input: String): Boolean = REGEX_PATTERN.containsMatchIn(input)
}

private val REGEX_PATTERN = """[0-9]+""".toRegex()
and yes, technically you can also drop the ": Boolean" but I like methods explicitly stating their return value 🤷‍♂️ and the Parser class looks kind of empty, the method isInputValid could be a top level function as well (without being nested in a class), in that case it should have a more descriptive name though.
Copy code
fun isInputValid(input: String): Boolean =
    REGEX_PATTERN.containsMatchIn(input)

private val REGEX_PATTERN =
    """[0-9]+""".toRegex()
Alternatively you use Parser as kind of a namespace and put isInputValid also into the companion class
Copy code
class Parser {
    companion object {
        @JvmStatic // not necessary, but an optimization  
        fun isInputValid(input: String): 
            Boolean = REGEX_PATTERN.containsMatchIn(input)
        @JvmStatic
        private val REGEX_PATTERN = """[0-9]+""".toRegex()
    }
}