Search code examples
scalaclassmethodscall

Scala: How to automaticly call method when class is declared?


For example, I have a class like this:

class SomeClass(val x:Int, val y: Int) {
 def someMethod(a: Int = x, b: Int = y) = new SomeClass(x + 1, y + 1)
 override def toString = x + " " + y
}

And I want the someMethod to be called when I declare the class. And the someMethod should change values x and y.

So when I execute the code:

val sc = new SomeClass(2, 5)
print(sc)

I'll expect this result:

3 6

Can you please help me with this?

This is what I need but in c# :

using System;
                    
public class Program
{
    public static void Main()
    {
        SomeClass sc = new SomeClass(2,5);
        Console.WriteLine(sc);
    }
}
public class SomeClass
{
    int x, y;
    public SomeClass(int x, int y) 
    {
        this.x = someMethod(x);
        this.y = someMethod(y);
    }
    int someMethod(int z)
    {
        return z + 1;
    }
    public override string ToString() 
    {
        return x + " " + y;
    }
}

Solution

  • You cannot change the values, since they are defined as val. val are defines a fixed value (which cannot be modified).

    What you can do, is defining the received values as private, and define other values, incremented:

    class SomeClass(private val xInternal:Int, private val yInternal: Int) {
      val x = xInternal + 1
      val y = yInternal + 1
      def someMethod(a: Int = x, b: Int = y) = new SomeClass(x + 1, y + 1)
      override def toString = s"$x $y"
    }
    
    val sc = new SomeClass(2, 5)
    

    Code run at Scastie.