Using Kotlin's @JvmOverloads with Android's Fragment.newInstance() pattern

时间:2017-11-08 22:00:00

标签: android kotlin

I've tried to accomplish this by defining the both as top-level fun and as a companion object static fun, but I get the same result. I'm able to see generated methods but there's none for newInstance(mouse: Mouse?) What am I misunderstanding about how this gets called from Java?

// MyFragment.kt
@JvmOverloads
fun newInstance(bird: Bird? = null, bee: Bee? = null, cat: Int? = -1, mouse: Mouse? = null) : MyFragment {
  //Put params in Bundle, put bundle in fragment...
  return MyFragment()
}

// MyActivity.java
MyFragment fragment = MyFragmentKt.newInstance(bird, bee, cat); // compiles
MyFragment fragment = MyFragmentKt.newInstance(mouse); // does not compile

1 个答案:

答案 0 :(得分:3)

The @JvmOverloads annotation makes the compiler generate all methods by leaving out the end-parameters. It does not generate methods for all permutations of parameters.

If a method has N parameters and M of which have default values, M overloads are generated: the first one takes N-1 parameters (all but the last one that takes a default value), the second takes N-2 parameters, and so on.

So MyFragmentKt.newInstance(bird) will exist, while MyFragmentKt.newInstance(mouse) or even MyFragmentKt.newInstance(bee) won't exist.