Is it possible to link javabean set methods?


#1

For  javabean , we usually have to write this: Bean obj = new Bean() obj.setA(...) obj.setB(...) obj.setC(...) ...

Maybe it would be more convenient this way:

obj~.setA()~.setB()~.setC() .

outersky


#2

You may write something like this:

class A(val a : String = "", val b : Int = 0) { }

A(a = “zzz”, b = 3)


Also note there are no methods setA and setB for class A

In some cases you can impelment with closure like this:

class A {   var x : Int = 0

  fun with(closure : A.() -> Unit) : Unit {
  closure()
  }

}

a().with { x = 1 }


But don’t play with it too much… this approach have visibility problems


#3

What if I have to use old java libraries ? There are pure javabeans everywhere.

Since in kotlin now we can do  list.filter(…).map(…).makeString(…) ,
I think it’s reasonable to make it more simple for using old javabeans.

thanks.

outersky


#4

One option is to say something like

with (obj) {   setA()   setB()   setC() }

Where with() is defined as follows:

fun <T> with(t : T, f : T.() -> Unit) {   t.(f)() }

Another would be to have an extension function for your obj:

fun MyPojo.set(a : A? = null, b : B? = null, c : C? = null) {   if (a != null) setA(a)   if (b != null) setB(b)   if (c != null) setC(c) }

// Usage

obj.set(a = aa, c = cc)


#5

wow , it works.

Now it’s the same as in javascript :smiley:

but I’m a little confused, for:

fun <T> with(t : T, f : T.() -> Unit) {
  t.(f)()
}

Shouldn’t the second parameter “f” mean ONE member function of Object “t” ?
While

{

setA()

setB()

setC()

}
means a group of functions .


#6

with (obj) {   setA();   foo(1); }

I’ve never made up my mind on whether this is a nice feature to have, any opinion on that? James?

Finally, two quick questions for Andrey:

What is the . for in:

f : T.() -> Unit

?

Also, your with definition only seems to allow for one statement, not multiple. Shouldn’t it be a varargs of closures?


#7

It doesn't mean a group of functions. It means "a function literal", you can think of it as a block of code, but in this block, this has type T


#8

What is the . for in:

f : T.() -> Unit

?

Also, your with definition only seems to allow for one statement, not multiple. Shouldn't it be a varargs of closures?

Please have a look at extension function literals.

#9

It does NOT work in M3. dropped or just a bug?


#10

It's not exactly droppped, but we don't do it currently, because it causes problems with inheritance.