Global extension function in Kotlin
Hi i want to create a class in kotlin that will contain all the extension functions that i will use in multiple places like:
class DateUtils {
//in this case I use jodatime
fun Long.toDateTime() : DateTime = DateTime(this)
fun String.toDateTime() : DateTime = DateTime.parse(this)
}
class SomeClassWithNoConnectionToDateUtils {
fun handleDataFromServer(startDate: String) {
someOtherFunction()
//startDate knows about toDateTime function in DateUtils
startDate.toDateTime().plusDays(4)
}
}
Is there a way to perform such an operation
+3
source to share
1 answer
Having extensions inside the class DateUtils
will make them available only for use inside the class DateUtils
.
If you want your extensions to be global, you can simply place them at the top level of the file without placing them in a class.
package com.something.extensions
fun Long.toDateTime() : DateTime = DateTime(this)
fun String.toDateTime() : DateTime = DateTime.parse(this)
And then import them to use them elsewhere:
import com.something.extensions.toDateTime
val x = 123456L.toDateTime()
+8
source to share