-13

I'm new to scala and i'm stuck with creating an object and adding it to an Object list in Scala. I want to do the below java implementation in scala. Please suggest a suitable approach.

class Foo {
    private int x;
    private int y;

    public Foo(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX(){
        return x;
    }
    public void setX(int x){
        this.x = x;
    } 
    public int getY(){
        return y;
    }
    public void setY(int y){
        this.y = y;
    }
}

class Main {
    List<Foo> fooList = new ArrayList<>();
    Foo foo = new Foo(1,2);
    fooList.add(foo);

} 
Tim
  • 26,753
  • 2
  • 16
  • 29
Nimphadora
  • 113
  • 2
  • 10

2 Answers2

3

This simplest way to do this is using a case class:

case class Foo(x: Int, y: Int)

class Main {
   def main(args: Array[String]) = {
     val myList = List(Foo(10, 20))
   }
}

However this code does not provide the modifiers setX and setY. The reason is that in Scala you usually create new objects rather than updating old ones. This keeps objects "immutable" and makes the code clearer and safer.

So rather than calling foo.setX(4) you would create a new foo with an updated value of x:

val newFoo = foo.copy(x = 4)

It takes a while to get used to writing code this way, but the features of Scala help to make this easier (e.g. the copy method above). The resulting code is safer and easier to understand because you know that x and y are not going to change under your feet.

This also encourages a more functional style where input values are transformed by a series of functions into output values. This is in contrast to an imperative style where input objects are mutated by methods which turn them into output objects.

Tim
  • 26,753
  • 2
  • 16
  • 29
-4

Tried the code below; it works.

class Foo(a: Int, b: Int) {
    var thisA: Double = a
    var thisB: Double = b
}

class Main {
    def main(args: Array[String]) = {

         var myList= List[Foo]()
         val listObject= new Foo(10,20)
         myList::= listObject
    }
}
Nimphadora
  • 113
  • 2
  • 10
  • 3
    It's better to avoid `var`s (and use `val`s). You should read about the difference between class and case class. Now you don't use `thisA`, `thisB`. – Dmytro Mitin Mar 09 '19 at 12:05