In Java, you'd have the Utils class with a bunch o...
# announcements
s
In Java, you'd have the Utils class with a bunch of static methods. Is there a more Kotlin-y preferred way of doing this?
r
Top level functions (there are a number of examples in the std lib, like
Strings.kt
,
Collections.kt
, etc.)
👍 1
s
Top level functions, either in their own file or as members of a relevant file
a
In addition, instead of creating static functions, it's common practice in Kotlin to use extension functions instead.
☝️ 4
s
thanks
h
Yeah, Kotlin helps keep the fundamental functionality of a class succinct and readable by allowing you to declare other methods for it in another file. Here's an example of a motivation to do such:
Copy code
class Sum(initial: Double = 0.0) {
   private var sum = initial
   
   operator fun plusAssign(num: Double) {
      sum += num
   }
}

// boilerplate stuff. 
// unneccessary to understand how the class works. 
// if declared in the class, only muddies up readability
operator fun Sum.plusAssign(num: Int) = plusAssign(num.toDouble())
If you want to declare a utility class with static methods in Kotlin (I can see why you may want to), use Kotlin's
Object
, which is analogous to a singleton class in Java:
Copy code
object Util { 
    fun parse(inputString: String) = ...
}
Often however there's no reason to do this over just declaring them top-level. note that top level functions can have visibility set like any internal functions or values