English 中文(简体)
能否在Schala确定构造-当地变量?
原标题:Is it possible to define a constructor-local variable in Scala?

以下代码取自Martin Odersky等人在Schala书中的方案规划。 界定合理类型:

class Rational(n: Int, d: Int) { 
  require(d != 0)
  private val g = gcd(n.abs, d.abs)
  val numer = n / g 
  val denom = d / g
  ...
  private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
}

这里,只有在隐含构造者初步确定田地数和den时才会使用价值克。 支持者们知道,在任何地方都使用它。 在上述情况下,在造价物后仍可使用。 也就是说,它也会占用空间,因为这是一个私人领域,而不是建筑商的一个当地变量。

我的问题是,我如何改变这一守则,以便“条码”——g只有在施工期间才使用,然后被抛弃?

最佳回答

在这种情况下,情况如何?

class Rational(n: Int, d: Int) {
  require(d != 0)
  val (numer, denom) = {
    val g = gcd(n.abs, d.abs)
    (n / g, d / g)
  }
  private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
}

<><>>><>><><>>><>>>>>>> 这还创造了一个额外领域,如编造的班级(比克、亚历克西)的<编码>javap所示:

public class Rational extends java.lang.Object implements scala.ScalaObject{
    private final scala.Tuple2 x$1; // actually unwanted!
    private final int numer;
    private final int denom;
    public int numer();
    public int denom();
    private int gcd(int, int);
    public Rational(int, int);
}

在其他情况下,我有时使用<代码>当地栏,以避免将每一条<代码>val变成一个领域:

class A {
  locally {
    val value1 = // ...
    val value2 = // ...
  }
}
问题回答

暂无回答




相关问题
UserControl constructor with parameters in C#

Call me crazy, but I m the type of guy that likes constructors with parameters (if needed), as opposed to a constructor with no parameters followed by setting properties. My thought process: if the ...

Strange "type class::method() : stuff " syntax C++

While reading some stuff on the pImpl idiom I found something like this: MyClass::MyClass() : pimpl_( new MyClassImp() ) First: What does it mean? Second: What is the syntax? Sorry for being such ...

Anonymous class question

I ve a little doubt over this line: An anonymous class cannot define a constructor then, why we can also define an Anonymous class with the following syntax: new class-name ( [ argument-list ] ) {...

Why copy constructor is not called in this case?

Here is the little code snippet: class A { public: A(int value) : value_(value) { cout <<"Regular constructor" <<endl; } A(const A& other) : value_(other....

Invoking an instance method without invoking constructor

Let s say I have the following class which I am not allowed to change: public class C { public C() { CreateSideEffects(); } public void M() { DoSomethingUseful(); } } and I have to call M ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

热门标签