Morgan
Morgan

Reputation: 313

Is the a way to use the default value of a non-nullable parameter when null is passed as an argument?

I looking for a way to have default values take the place of nulls when passed as arguments. My motivation is purely to reduce the amount of code written (I want to avoid having overloaded functions/constructors or manual 'if null' checks)

My use case is within a Spring RestController, I want default values of a method called by the controller to be used without needing to state those default values outside the function.

I thought perhaps that using named parameters might provide this functionality but my experiments show otherwise. Perhaps there is a way with the elvis operator?

Example Code:

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
}

Hopefully you can help

Upvotes: 0

Views: 657

Answers (2)

Nizan Ifrach
Nizan Ifrach

Reputation: 141

The @RequestParam annotation has a default value option named "defaultValue". you can use it like so:

@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
}

Upvotes: 1

zsmb13
zsmb13

Reputation: 89548

There aren't any specific language features that would do this for you, the default argument mechanism isn't connected to nullability in any way.

However, you can achieve this in a more manual fashion by making your parameters nullable, and immediately substituting default values inside the function if they're 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
}

Upvotes: 2

Related Questions