[英]Kotlin optional parameter with Java backwards compatibility
我目前正在編寫一個 Kotlin 庫,其中 object 具有需要多個可選參數的多種方法。 由於在 JAVA 中,您需要將 null 傳遞給這些參數,我認為這有點不舒服。 重載也不是解決方案,因為我不一定知道可能的組合,或者有很多可能性的方法。
class MyObj() {
fun method1(param1: Int, param2: String? = null, param3: Int? = null): String { ... }
fun method2(param1: Int, param2: Float? = null, param3: String? = null): Any { ... }
fun method5(param1: Int, ...): User { ... }
}
在 Kotlin 我可以簡單地寫:
myObj = MyObj()
myObj.method1(param1 = 4711, param3 = 8850)
在 Java 我需要寫:
MyObj myObj = new MyObj()
myObj.method1(4711, null, 8850)
...
myObj.method5("abc", null, null, null, null, 8850, null, null, "def")
由於我有很多帶有很多選項的方法,我想只為每種方法傳遞一個 class :
/** For JAVA backwards compatibility */
class Method1(
val param1: Int
) {
param2: String? = null
param3: Int? = null
fun withParam2(value: String) = apply { param2 = value }
fun withParam3(value: Int) = apply { param3 = value }
}
class MyObj() {
fun method1(param1: Int, param2: String? = null, param3: Int? = null): String { ... }
/** For JAVA backwards compatibility */
fun method1(values: Method1) = method1(values.param1, values.param2, values.param3)
}
所以在 Kotlin 我可以使用命名參數,在 Java 我可以簡單地寫:
MyObj myObj = new MyObj()
myObj.method1(new Method1(4711).withParam3(8850))
從我的角度來看,它看起來相當難看,因為我總是不得不說method1(new Method1())
或method2(new Method2())
。 你認為有一個更優雅的版本嗎?
背景:這是為了調用帶有大量可選參數的 REST API。
對於 Java,處理大量可選 arguments 的最佳方法通常是通過某種形式的構建器模式。 我會建議以下兩種變體之一:
1:返回一個可鏈接的 object 並在最后使用某種“運行”方法來獲取提供的 arguments 並運行實際方法。
myObj.retrieveWhatever().from("abc").where(LESS_THAN, 3).setAsync(true).run();
2:對於 Java 8+,執行相同操作,但在 lambda 中:
myObj.retrieveWhatever(args ->
args.from("abc").where(LESS_THAN, 3).setAsync(true)
);
...或者,或者,
myObj.retrieveWhatever(args -> {
args.from("abc");
args.where(LESS_THAN, 3);
args.setAsync(true);
});
通過在 lambda 中執行此操作,您消除了最后忘記.run()
調用的風險。
您可以為函數添加@JvmOverloads
注釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.