Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I alias the scala setter method 'myvar_$eq(myval)' to something more pleasing when in java?

I've been converting some code from java to scala lately trying to teach myself the language.

Suppose we have this scala class:

class Person() {
  var name:String = "joebob"
}

Now I want to access it from java so I can't use dot-notation like I would if I was in scala.

So I can get my var's contents by issuing:

person = Person.new();
System.out.println(person.name());

and set it via:

person = Person.new();
person.name_$eq("sallysue");
System.out.println(person.name());

This holds true cause our Person Class looks like this in javap:

Compiled from "Person.scala"
public class Person extends java.lang.Object implements scala.ScalaObject{
    public Person();
    public void name_$eq(java.lang.String);
    public java.lang.String name();
}

Yes, I could write my own getters/setters but I hate filling classes up with that and it doesn't make a ton of sense considering I already have them -- I just want to alias the _$eq method better. (This actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like person.name_\$eq("newname");

Note: I'd much rather have to put up with this rather than fill my classes with more setter methods.

So what would you do in this situation?

like image 656
eyberg Avatar asked Mar 12 '10 18:03

eyberg


People also ask

How do you create a getter and setter in Scala?

Scala generates a class for the JVM with a private variable field and getter and setter methods. In Scala, the getters and setters are not named getXxx and setXxx, but they are used for the same purpose. At any time, we can redefine the getter and setter methods ourself.

Which action will automatically create a getter and setter for a class in Scala?

When you define a class field as a var , Scala automatically generates getter and setter methods for the field, and defining a field as a val automatically generates a getter method, but you don't want either a getter or setter.


1 Answers

You can use Scala's bean property annotation:

class Person() {
  @scala.reflect.BeanProperty
  var name:String = "joebob"
}

That will generate getName and setName for you (useful if you need to interact with Java libraries that expect javabeans)

like image 132
GClaramunt Avatar answered Oct 15 '22 21:10

GClaramunt