16

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

Gil Goldzweig
  • 1,809
  • 1
  • 13
  • 26

1 Answers1

36

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()
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • 1
    Thanks for the quick reply and sorry for the noob question but I'm new at kotlin coming from Java.how can I use data in a constructor to use in the function? – Gil Goldzweig Jun 03 '17 at 19:06
  • 1
    No worries, it was a perfectly reasonable question. Have fun with Kotlin :) – zsmb13 Jun 03 '17 at 19:07