たとえば、いくつかの場所で使用するすべての拡張関数を保持するクラスを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)
}
}
そのような操作を実行する方法はありますか
拡張機能をDateUtils
クラス内に置くと、それらはDateUtils
クラス内でのみ使用できるようになります。
拡張機能をグローバルにしたい場合は、クラス内に配置せずに、ファイルの最上位に配置することができます。
package com.something.extensions
fun Long.toDateTime() : DateTime = DateTime(this)
fun String.toDateTime() : DateTime = DateTime.parse(this)
そして、それらをインポートして、次のように他の場所で使用します。
import com.something.extensions.toDateTime
val x = 123456L.toDateTime()