嘿,我想在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)
}
}
有没有办法执行此类操作
1 回答
将扩展放在
DateUtils
类中将使它们仅在DateUtils
类中使用 .如果您希望扩展是全局的,您可以将它们放在文件的顶层,而不必将它们放在类中 .
然后导入它们以在其他地方使用它们: