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

推荐答案

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()

Kotlin相关问答推荐

直接从SON解析NonEmptyList

Android前台服务 list —Altbeacon

用浮点数或十进制数给出错误答案的阶乘计算

使用另一个对象的列表创建对象

可以从背景图像中点击图标吗?

Criteria Api 中的 Kotlin 泛型

generic 类实例列表 - 调用采用 T 的函数

Ktor 在 Heroku 上的 CORS 问题,但在本地没有

Kotlin 数据类中的大量参数

Kotlin 中的密封和内部有什么区别?

在 Kotlin 协程中切换 IO 和 UI 的正确方法是什么?

如何连接两个 kotlin 流?

如何在 Android 的 Fragment 中使用 setUserVisibleHint

是否可以在 kotlin 中嵌套数据类?

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

在 Kotlin 中实现 (/inherit/~extend) 注解

如何在协程之外获取 Flow 的值?

Kotlin数据类打包

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?

Kotlin:获取文件的扩展名,例如.txt