Is it good practice to use @BeanProperty in Scala instead of defining getter / setter functions?

Defining data members in a class access to which you can publish / modify

var _foo: Int = _
def foo_(foo: Int) = _foo = foo    // setter function
def foo = _foo                     // getter function

Is it good to convert using annotations @BeanProperty?

import scala.reflect.BeanProperty
@BeanProperty var foo: Int = _

and when to use this annotation, and if not?

+4
source share
2 answers

There is redundancy in your first example, since the definition varalready leads to the generation of getters and setters. For example, if we compile this class:

class Foo {
  var foo: Int = _
}

Then javap -private Fooshows the following:

public class Foo {
  private int foo;
  public int foo();
  public void foo_$eq(int);
  public Foo();
}

, ( ), .

scala.reflect.BeanProperty ( scala.beans.BeanProperty 2.11) foo() foo_$eq(int) - var foo: Int, , . getFoo setFoo . , , , .

:

  • var.
  • var, ( ) .
  • BeanProperty , getFoo setFoo, , Java ( , foo_$eq ).
+8

@BeanProperty Java, , get set.

, Scala. Scala getters (def foo) (def foo_=).

+3

Source: https://habr.com/ru/post/1626185/


All Articles