Moch. Chamdani
Moch. Chamdani

Reputation: 11

what should I do if I want to set the default value of my parameter if the parameter has null value

How to set the default value of the variable valueC if the valueC is null, and then get the default value for valueC = 100 in elvis operator.

// Here my full code 

fun main() {
    val valueA = 65
    val valueB = 52
    val valueC = 78

    val result = calculate(valueA, valueB, valueC)

    // TODO 3
    println("Result is $result")
}

fun calculate(valueA: Int, valueB: Int, valueC: Int?=100): String {
    // TODO 1
    val result = valueC?.let { valueA + (valueB - valueC) } ?: 100
    return generateResult(result)
}

// TODO 2
fun generateResult(result: Int) = result.toString()

Upvotes: 1

Views: 6778

Answers (3)

jsamol
jsamol

Reputation: 3232

If valueC is null, give 100 for the default value.

You can use the elvis operator when you use valueC in any expression:

fun calculate(valueA: Int, valueB: Int, valueC: Int?): String {
    val result = valueA + (valueB - (valueC ?: 100))
    return generateResult(result)
}

or shadow the valueC name, setting the new variable to a default value if valueC is null or leave the original value otherwise:

fun calculate(valueA: Int, valueB: Int, valueC: Int?): String {
    val valueC = valueC ?: 100

    val result = valueA + (valueB - valueC)
    return generateResult(result)
}

Upvotes: 1

Sasi Kumar
Sasi Kumar

Reputation: 13288

Your parameter should be like this

calculate(valueA: Int, valueB: Int, valueC: Int =100)  
// if valuec is null 100 is the default value of C

full sample program

fun main() {
//without param c value
println(calculate(5,10))      //output -85
 // with param c value
println(calculate(5,10,5))     //output 10

}

fun calculate(valueA: Int, valueB: Int, valueC: Int =100): String {
val result = valueC?.let { valueA + (valueB - it) }
return generateResult(result)
}



fun generateResult(result:Int):String
{
return result.toString()
}

Upvotes: 0

vishal jangid
vishal jangid

Reputation: 3025

Kotlin supports default arguments in function declarations. You can specify a default value for a function parameter. The default value is used when the corresponding argument is omitted from the function call.

fun displayGreeting(message: String, name: String = "Guest") {
  println("Hello $name, $message")
}


displayGreeting("Welcome to the CalliCoder Blog", "John") // Hello John, Welcome to the CalliCoder Blog

However, If you omit the argument that has a default value from the function call, then the default value is used in the function body -

displayGreeting("Welcome to the CalliCoder Blog") // Hello Guest, Welcome to the CalliCoder Blog

Upvotes: 0

Related Questions