这应该很简单.如何将函数应用于Scala中的元组?即:
scala> def f (i : Int, j : Int) = i + j f: (Int,Int)Int scala> val p = (3,4) p: (Int, Int) = (3,4) scala> f p :6: error: missing arguments for method f in object $iw; follow this method with `_' if you want to treat it as a partially applied function f p ^ scala> f _ p :6: error: value p is not a member of (Int, Int) => Int f _ p ^ scala …
在Java的构造函数中,如果要调用另一个构造函数(或超级构造函数),它必须是构造函数中的第一行.我假设这是因为在其他构造函数运行之前不应该允许修改任何实例变量.但是为什么你不能在构造函数委托之前有语句,以便计算其他函数的复杂值?我想不出任何好的理由,而且我遇到了一些真实的案例,我写了一些丑陋的代码来解决这个限制.
所以我只是想知道:
举一个我正在谈论的例子,考虑一下我在StackOverflow中给出的一些代码.在那段代码中,我有一个BigFraction类,它有一个BigInteger分子和一个BigInteger分母."规范"构造函数是BigFraction(BigInteger numerator, BigInteger denominator)
表单.对于所有其他构造函数,我只是将输入参数转换为BigIntegers,并调用"规范"构造函数,因为我不想复制所有工作.
在某些情况下,这很容易; 例如,带两个long
s 的构造函数是微不足道的:
public BigFraction(long numerator, long denominator)
{
this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));
}
Run Code Online (Sandbox Code Playgroud)
但在其他情况下,这更难.考虑采用BigDecimal的构造函数:
public BigFraction(BigDecimal d)
{
this(d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(),
d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale()));
}
Run Code Online (Sandbox Code Playgroud)
我觉得这很难看,但它有助于我避免重复代码.以下是我想要做的,但它在Java中是非法的:
public BigFraction(BigDecimal d)
{
BigInteger numerator = null;
BigInteger denominator = null;
if(d.scale() < 0)
{
numerator = d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()));
denominator = BigInteger.ONE;
}
else
{
numerator = d.unscaledValue();
denominator = BigInteger.TEN.pow(d.scale());
}
this(numerator, …
Run Code Online (Sandbox Code Playgroud) 有没有办法重载一个构造函数而不仅仅是一个单行构造函数?似乎在重载的构造函数中放置一个以上的语句会产生错误Application does not take parameters
。例如,如果主构造函数采用 a String
,则以下将起作用:
def this(num: Int) = {
this(num.toString())
}
Run Code Online (Sandbox Code Playgroud)
但是,以下情况不会:
def this(num: Int) = {
val numAsString = num.toString()
this(numAsString)
}
Run Code Online (Sandbox Code Playgroud)