0

I have method with 10+ parameters actually I should write it with builder pattern. However, I think it will be a mess when converted to Kotlin. I wonder if there is a way to write java that could easily act like Kotlin does?

When we created fun with Kotlin like this

fun foo(bar: Int = 0, baz: Int) { /* ... */ }

foo(baz = 1) // The default value bar = 0 is used

How can we write similar method in java without written every possible?

E.g.

don't need to write

void foo(int bar, int baz){
...
}

void foo(int baz){
int bar = 0;
}
UmAnusorn
  • 10,420
  • 10
  • 72
  • 100

1 Answers1

3

Not really closest thing you have is something like this

void foo(int bar, int baz){
  ...
}

void foo(int baz){
    foo(0,baz);
}
urag
  • 1,228
  • 9
  • 28
  • Nice answer but what if you have 10+ params. That's gonna be so many methods. – UmAnusorn Sep 03 '17 at 13:25
  • I am not sure, but I think that if you look into decompiled kotlin code, you will see exactly this as (imo) is how kotlin handles default parameters in bytecode. – Maroš Šeleng Sep 03 '17 at 13:27
  • 1
    @umitems IMO if you have that many params you should try to refactor the method – Mibac Sep 03 '17 at 13:27
  • 1
    @MarošŠeleng Kotlin does not generate code like this. It generates a normal method with all the params and a second one only for Kotlin to use with all the params and a int at the end and basing on the int it uses default params or the supplied ones – Mibac Sep 03 '17 at 13:29
  • I think the difference comes from the language type java is static type and kotlin is dinmaic type that's the reason you cannot do this in java here is a link about this issue https://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages – urag Sep 03 '17 at 13:31
  • 2
    @urag Kotlin *is* statically typed with the only exception being when compiling to JavaScript - then you have a `dynamic` type (it's still statically typed, this is used when e.g. you don't know what type the variable will be) – Mibac Sep 03 '17 at 13:32
  • @MarošŠeleng I've decompiled a Kotlin function in the question and got [this code](https://pastebin.com/7PCE7HKU) – Mibac Sep 03 '17 at 13:40
  • @umitems a method with 10 parameters needs to be refactored. General practice suggests that your method should require no more than 4 parameters. While this is not a hard rule, a method with too many parameters is very unwieldy. – Joshua Jones Sep 03 '17 at 14:13
  • 1
    @jjones As I mentioned that it will be better to written on builder pattern if I written in java. Its the builder for custom dialog. – UmAnusorn Sep 03 '17 at 14:16