https://kotlinlang.org logo
Title
z

zceejkr

10/23/2019, 12:46 PM
Hi, one question: What is the difference between declaring a function as a val vs declaring it as a fun on a class? I read somewhere that when calling from Java, the one defined with val becomes cumbersome to use. Is that still the case?
g

gildor

10/23/2019, 1:00 PM
Property will just look as a getter from Java (with is or get prefix), but you also can rename it using JvmName
So nothing cumbersome
z

zceejkr

10/23/2019, 1:01 PM
so to call it I would need to do something like obj.getFun().invoke(args) vs obj.fun(args)?
g

gildor

10/23/2019, 1:02 PM
No real difference on Kotlib side, only semantics a bit different, you can check official style guide, it have some recommendations when use properties when functions
No, your example is incorrect
Obviously you cannot use properties with parameters
Property may be used only as replacement for a getter without arguments
Your example above looks that property foo returns lambda, not just value, it's valid itself, but not as replacement for fun(args)
So simple comparison would be: val foo = 1 In Java would be obj.getFoo()
z

zceejkr

10/23/2019, 1:07 PM
I see, I think I understand. But what is the difference between fun(args) and a returned lambda that captures the “this” keyword of the object it is a property of?
Calling the fun or the lambda should do the same thing no?
In any case thanks for the help.
a

Alowaniak

10/23/2019, 3:26 PM
Using a val which returns a function type to use as a normal function is kind of a weird style I would say It might make sense if you use it as a value more often than immediately invoking?
z

zceejkr

10/23/2019, 3:32 PM
So the reason I want to use it so that I can use destructuring in the arguments XD. As I understand you cannot do that in a fun?
a

Alowaniak

10/23/2019, 4:05 PM
Hmyea it's currently not possible to do destructured params I personally don't think I would use your lambda val approach though You can just do a destructured declaration on the first line of the function
z

zceejkr

10/23/2019, 4:56 PM
I see. Well thank you for your help 🙂
g

gildor

10/23/2019, 11:21 PM
if you use it as a value more often
True, but in this case client may decide and just wrap to lambda on call site or use property reference syntax
destructuring in arguments
Just use local variable for destructuring, do not pollute caller's API with unnecessary lambda call