在设置值之前修改案例类构造函数参数 [英] Modifying case class constructor parameter before setting value

查看:60
本文介绍了在设置值之前修改案例类构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中有没有办法修改传递给单参数 case 类构造函数/apply() 方法的参数,然后它会变成 val?例如

Is there a way in Scala to modify a parameter passed to a single-argument case class constructor / apply() method before it becomes a val? E.g.

case class AbsVal private(aVal: Double)

object AbsVal {
    def apply(aVal: Double): AbsVal = AbsVal(Math.abs(aVal)) // doesn't compile
}

这当然会失败,因为对重载定义的引用不明确.我想也许我可以用命名参数(以及构造函数与 apply() 的不同参数名称)来欺骗它,但这也不起作用.

This fails of course with ambiguous reference to overloaded definition. I thought maybe I could trick it with named parameters (and different parameter names for the constructor vs apply()), but that doesn't work either.

当然,除了 apply() 我可以只拥有私有构造函数和工厂方法,但是不得不用 AbsVal.make(x) 乱扔代码很烦人code> 而不是 AbsVal(x).

Of course instead of apply() I could just have the private constructor and a factory method, but it's annoying to have to litter the code with AbsVal.make(x) instead of just AbsVal(x).

推荐答案

abstract case class AbsVal private(value: Double)

object AbsVal {
  def apply(value: Double): AbsVal = new AbsVal(Math.abs(value)) {}
}

抽象案例类没有在其伴生对象中自动生成的应用方法.这让我们可以创建自己的.我们必须创建另一个类来继承 case 类(这里是匿名的),但是为 case 类生成的 toString 方法仍然会将其显示为 AbsVal,所以这也应该是不可见的.copy 方法不会为抽象案例类自动生成,但对于具有这样单个参数的类,无论如何它都没有用(并且它始终可以手动定义,请参阅 LimbSoup 的答案).

Abstract case classes don't have an apply method automatically generated in their companion object. This lets us create our own. We have to create another class to inherit from the case class (anonymous, here), but the toString method generated for the case class will still display it as an AbsVal, so this should be invisible as well. A copy method is not automatically generated for abstract case classes, but for a class with a single parameter like this it wouldn't be useful anyway (and it can always be defined manually, see LimbSoup's answer).

案例类继承通常是一个坏主意,但是由于私有构造函数,唯一存在的子类将是我们定义的匿名子类,因此在这种情况下它是安全的.

Case class inheritance is usually a bad idea, but because of the private constructor the only subclass that will exist will be the anonymous one we define, so in this instance it is safe.

这篇关于在设置值之前修改案例类构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆