当 null 作为参数传递时,是否可以使用不可为 null 的参数的默认值?
Is the a way to use the default value of a non-nullable parameter when null is passed as an argument?
我正在寻找一种方法,让默认值在作为参数传递时代替空值。我的动机纯粹是为了减少编写的代码量(我想避免超载 functions/constructors 或手动 'if null' 检查)
我的用例在 Spring RestController 中,我希望使用控制器调用的方法的默认值,而无需在函数外声明这些默认值。
我认为也许使用命名参数可以提供此功能,但我的实验表明情况并非如此。也许猫王运算符有办法?
示例代码:
fun someFunction(first: Long = 1, second: Int = 2 ) {
// Do something
}
@GetMapping
fun someEndpoint(@RequestParam("first") firstParam: Long?):ResponseEntity<Any> {
someFunction(firstParam) // Attempt 1: "Required: Long\n Found: Long?
someFunction(first = firstParam) // Attempt 2: Same error
}
希望你能帮上忙
没有任何特定的语言功能可以为您执行此操作,默认参数机制与可空性没有任何关系。
但是,您可以通过使参数可为 null 并在函数内立即替换为 null 的默认值来以更手动的方式实现此目的:
fun someFunction(first: Long? = null, second: Int? = null) {
val actualFirst: Long = first ?: 1
val actualSecond: Int = second ?: 2
// Do something with actualFirst and actualSecond
}
@RequestParam 注释有一个名为 "defaultValue" 的默认值选项。
你可以这样使用它:
@GetMapping
fun someEndpoint(@RequestParam(name = "first", defaultValue = "1") firstParam: Long):ResponseEntity<Any> {
someFunction(firstParam) // firstParam equals to 1 if null was passed to the endpoint
}
我正在寻找一种方法,让默认值在作为参数传递时代替空值。我的动机纯粹是为了减少编写的代码量(我想避免超载 functions/constructors 或手动 'if null' 检查)
我的用例在 Spring RestController 中,我希望使用控制器调用的方法的默认值,而无需在函数外声明这些默认值。
我认为也许使用命名参数可以提供此功能,但我的实验表明情况并非如此。也许猫王运算符有办法?
示例代码:
fun someFunction(first: Long = 1, second: Int = 2 ) {
// Do something
}
@GetMapping
fun someEndpoint(@RequestParam("first") firstParam: Long?):ResponseEntity<Any> {
someFunction(firstParam) // Attempt 1: "Required: Long\n Found: Long?
someFunction(first = firstParam) // Attempt 2: Same error
}
希望你能帮上忙
没有任何特定的语言功能可以为您执行此操作,默认参数机制与可空性没有任何关系。
但是,您可以通过使参数可为 null 并在函数内立即替换为 null 的默认值来以更手动的方式实现此目的:
fun someFunction(first: Long? = null, second: Int? = null) {
val actualFirst: Long = first ?: 1
val actualSecond: Int = second ?: 2
// Do something with actualFirst and actualSecond
}
@RequestParam 注释有一个名为 "defaultValue" 的默认值选项。 你可以这样使用它:
@GetMapping
fun someEndpoint(@RequestParam(name = "first", defaultValue = "1") firstParam: Long):ResponseEntity<Any> {
someFunction(firstParam) // firstParam equals to 1 if null was passed to the endpoint
}