scala - 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;
}
}
解决方案
首先,您希望它在类被实例化但未声明时执行。
其次,如果这在一般意义上是可能的,那将导致代码难以理解。
第三,尚不清楚您是否要变异x
和y
或仅返回一个新值。
第四,如果是后者,这将导致无限循环并且代码永远不会完成。
第五,为什么不只是这样?
final case class SomeClass(x: Int, y: Int)
object SomeClass {
def apply(x: Int, y: Int): SomeClass =
new SomeClass(x + 1, y + 1)
}
推荐阅读
- docker - 如何使用 postgres 对接 PDI 作业?
- c++ - "strtol" 返回不同的值
- javascript - 如何使用输入编号框同时增加产品数量和成本。使用 JavaScript
- javascript - 提取天气 API 数据并发布推文
- angular - 无法调整画布大小
- python - 当回到Django中每个选项卡的子级时如何保持在同一个选项卡上
- python - 在机器人框架中退出 For 循环
- java - Hibernate 不通过 SequenceGenerator 生成 ID
- laravel - 如何从表中获取所有行,与数据透视表连接是否有关系?
- php - 如何在php中传递数组中的对象?