Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global extension function in kotlin

Hey I want to make a class in kotlin that will hold all extension functions that I will use in a few places for example:

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 operation

like image 320
Gil Goldzweig Avatar asked Jun 03 '17 18:06

Gil Goldzweig


People also ask

How do you make a function Global on Kotlin?

Having your extensions inside a DateUtils class will make them available for use only inside the DateUtils class. If you want the extensions to be global, you can just put them on the top level of a file, without putting them inside a class.

What are the extension functions in Kotlin?

Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any type of design pattern. The created extension functions are used as a regular function inside that class. The extension function is declared with a prefix receiver type with method name.

What is the purpose of Kotlin extension function?

The Kotlin extension allows to write new functions for a class from a third-party library without modifying the class. The beauty of the extension functions is that they can be called in the usual way, as if they were methods of the original class and these new functions are called Extension Functions.


1 Answers

Having your extensions inside a DateUtils class will make them available for use only inside the DateUtils class.

If you want the extensions to be global, you can just put them on the top level of a file, without putting them inside 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 like so:

import com.something.extensions.toDateTime

val x = 123456L.toDateTime()
like image 50
zsmb13 Avatar answered Oct 21 '22 01:10

zsmb13