https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Dontsu

10/23/2023, 5:28 AM
Do these kind of functions have performance problems? I haven't seen a lot of people use "if" in a parameter for a function.
fun getPrice(
productCount : Int,
discount: Int,
limit = if (productCount == 12) 3 else 6
) {
// codes..
}
As you can see, the parameter
limit
is determined by
productCount
. I just wonder it would be a performance problem when runtime or compiler checks this function would often be changed or not. Of course, Kotlin has immutable parameters in a function but the "if" can be a problem??
s

Sam

10/23/2023, 7:30 AM
There's no performance issue. A default parameter expression is evaluated when you call the function, just the same as if you used that expression as an explicit argument. The reason you don't see code like this very often is probably more to do with style and readability. People don't expect to see logic inside a function signature, so I think it's best to keep default parameter values as simple as possible.
r

Ronny Bräunlich

10/23/2023, 7:30 AM
If you check the decompiled code it's just an `if`:
Copy code
public static void getPrice$default(MediaConsumedProcessor var0, int var1, int var2, int var3, int var4, Object var5) {
      if ((var4 & 4) != 0) {
         var3 = var1 == 12 ? 3 : 6;
      }

      var0.getPrice(var1, var2, var3);
   }
Apart from this, it's somehow strange behaviour to have a derived parameter. Since I could pass in a
productCount
of 12 and still set
limit
to 6.
d

Dontsu

10/25/2023, 12:20 AM
Thank you guys!