how can i make a function with optional non nullab...
# getting-started
p
how can i make a function with optional non nullable parameter which will use the default when i pass in null?
s
non nullable parameter pass in null pick 1
p
null should mean the same thing as omit, IMHO
s
That ship has sailed and it doesnt.
e
No it shouldn't, as it leads to unexpected behavior in some cases
s
But if you want to pass in null what is the problem with making it nullable ?
Cant you just do
Copy code
fun foo(input: String? = null){
val inputOrDefault = input ?: "default"
}
p
it's ugly
i know have to specify two "defaults"
one null and one actual default that i want
s
Yes but Kotlin is not how you want it to be. Cant change that. So now you have to choose if you want it to be nice for the caller or for the implementation.
h
why not just make it
fun foo(input: String = "defaults")
p
because then i cant pass in a nullable variable
s
take a look at decompiled code for function overloading
it uses a bridge method to do that work using bitmask
Copy code
public static final void fooBar(int value, int optionalValue) {
   }

   // $FF: synthetic method
   // $FF: bridge method
   public static void fooBar$default(int var0, int var1, int var2, Object var3) {
      if ((var2 & 2) != 0) {
         var1 = 5;
      }

      fooBar(var0, var1);
   }
h
Copy code
fun foo(a: String? ) {
foo(a?: "defaults")
}

fun foo(a: String) {

}
1