kotlin中的全局扩展功能

Gil*_*eig 12 kotlin extension-function

嘿,我想在kotlin中创建一个类,它将包含我将在几个地方使用的所有扩展函数,例如:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法执行此类操作

zsm*_*b13 21

DateUtils类中使用扩展将使它们仅在DateUtils类中使用.

如果您希望扩展是全局的,您可以将它们放在文件的顶层,而不必将它们放在类中.

package com.something.extensions

fun Long.toDateTime() : DateTime = DateTime(this)
fun String.toDateTime() : DateTime = DateTime.parse(this)
Run Code Online (Sandbox Code Playgroud)

然后导入它们以在其他地方使用它们:

import com.something.extensions.toDateTime

val x = 123456L.toDateTime()
Run Code Online (Sandbox Code Playgroud)