https://kotlinlang.org logo
#announcements
Title
# announcements
s

Steve

12/02/2019, 5:02 PM
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

Ruckus

12/02/2019, 5:03 PM
Top level functions (there are a number of examples in the std lib, like
Strings.kt
,
Collections.kt
, etc.)
👍 1
s

serebit

12/02/2019, 5:04 PM
Top level functions, either in their own file or as members of a relevant file
a

adimit

12/02/2019, 5:04 PM
In addition, instead of creating static functions, it's common practice in Kotlin to use extension functions instead.
☝️ 4
s

Steve

12/02/2019, 5:07 PM
thanks
h

Hullaballoonatic

12/02/2019, 6:35 PM
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