首页 > 解决方案 > Scala:声明类时如何自动调用方法?

问题描述

例如,我有一个这样的类:

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
}

我希望在声明类时调用 someMethod 。并且 someMethod 应该改变 x 和 y 的值。

所以当我执行代码时:

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

我会期待这个结果:

3 6

你能帮我解决这个问题吗?

这是我需要的,但在 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;
    }
}

标签: scalaclassmethodscall

解决方案


首先,您希望它在类被实例化但未声明时执行。

其次,如果这在一般意义上是可能的,那将导致代码难以理解。

第三,尚不清楚您是否要变异xy或仅返回一个新值。

第四,如果是后者,这将导致无限循环并且代码永远不会完成。

第五,为什么不只是这样?

final case class SomeClass(x: Int, y: Int)

object SomeClass {
  def apply(x: Int, y: Int): SomeClass =
    new SomeClass(x + 1, y + 1)
}

推荐阅读