Accessing a function's default parameter value in Kotlin -


can function's default parameter value accessed function extension, or anywhere else?

fun dieroll.cheatroll():int = roll(min = max -1)  fun roll(min: int = 1, max: int = 6): int = (min..max).rand() 

no, not possible. default values not accessible. contained in bridge-method in bytecode:

fun test(a: int = 123) { }  fun test2() {     test()     test(100) } 

results in bytecode:

public final test(int arg0) { //(i)v      <localvar:index=0 , name=this , desc=lorg/guenhter/springboot/kt/fun;, sig=null, start=l1, end=l2>      <localvar:index=1 , name=a , desc=i, sig=null, start=l1, end=l2>       l1 {          return      }      l2 {      }  }   public static bridge test$default(org.guenhter.springboot.kt.fun arg0, int arg1, int arg2, java.lang.object arg3) { //(lorg/guenhter/springboot/kt/fun;iiljava/lang/object;)v          iload2 // reference arg2          iconst_1          iand          ifeq l1      l2 {          bipush 123  // <-- default value          istore1 // reference arg1      }      l1 {          aload0 // reference arg0          iload1 // reference arg1          invokevirtual org/guenhter/springboot/kt/fun test((i)v);          return      }  }   public final test2() { //()v      <localvar:index=0 , name=this , desc=lorg/guenhter/springboot/kt/fun;, sig=null, start=l1, end=l2>       l1 {          aload0 // reference self          iconst_0          iconst_1          aconst_null          invokestatic org/guenhter/springboot/kt/fun test$default((lorg/guenhter/springboot/kt/fun;iiljava/lang/object;)v);      }      l3 {          aload0 // reference self          bipush 100          invokevirtual org/guenhter/springboot/kt/fun test((i)v);      }      l4 {          return      }      l2 {      }  } 

so best alternative extract default value constant:

private val default_min = 1 private val default_max = 1  fun dieroll.cheatroll():int = roll(min = default_max-1)  fun roll(min: int = default_min, max: int = default_max): int = (min..max).rand() 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -