【问题标题】:Scala: How to automaticly call method when class is declared?Scala:声明类时如何自动调用方法?
【发布时间】:2021-03-09 12:08:29
【问题描述】:

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

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;
    }
}

【问题讨论】:

    标签: scala class methods call


    【解决方案1】:

    您无法更改这些值,因为它们被定义为val。 val 定义了一个固定值(不能修改)。

    您可以做的是将接收到的值定义为私有值,并定义其他值,递增:

    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)
    

    代码在Scastie 运行。

    【讨论】:

      【解决方案2】:

      首先,你希望它在类被实例化而不声明时执行。

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

      第三,不清楚是要改变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)
      }
      

      【讨论】:

      • 嘿,我通过 C# 中的示例指定了我需要的内容
      • @baltek99 首先不要假设人们会理解另一种语言。其次,您希望x 和y 不可变但同时可变。第三,我不知道C# 但是AFAIK不建议在构造函数期间调用方法,对象甚至不存在。第四,我仍然不明白为什么我的建议让你自己的工厂方法为你做这件事是行不通的。
      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      相关资源
      最近更新 更多