y
10/11/2022, 11:43 AMVitor Hugo Schwaab
10/11/2022, 11:48 AMclass 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:
const val BAR = "bar"
class Foo {
fun doSomething() {
println("BAR = $BAR")
}
}
More about it:
• Companion objects
• Objectsy
10/11/2022, 11:52 AMy
10/11/2022, 11:55 AMVitor Hugo Schwaab
10/11/2022, 11:56 AMclass Parser {
fun isInputValid(input: String): Boolean {
return REGEX_PATTERN.containsMatchIn(input)
}
private companion object {
val REGEX_PATTERN = """[0-9]+""".toRegex()
}
}
Vitor Hugo Schwaab
10/11/2022, 11:57 AMy
10/11/2022, 11:59 AMy
10/11/2022, 11:59 AMy
10/11/2022, 12:00 PMLandry Norris
10/11/2022, 12:57 PMclass Parser {
fun isInputValid(input: String): Boolean {
return REGEX_PATTERN.containsMatchIn(input)
}
}
private val REGEX_PATTERN = """[0-9]+""".toRegex()
Landry Norris
10/11/2022, 12:58 PMKlitos Kyriacou
10/11/2022, 2:50 PMStephan Schroeder
10/11/2022, 4:35 PMclass 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.
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
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()
}
}