在 Scala 中为 case 类创建伴随对象时遇到问题



我正在使用带有Scala的Kaggle数据集进行一些探索性分析。我要做的一件事是为名为"Taxpayer"的案例类创建一个伴随对象,如下所示:

case class Taxpayer(
age: Int,
workclass: String,
education: String,
educationNum: Int,
maritalStatus: String,
occupation: String,
relationship: String,
race: String,
sex: String,
capitalGain: Int,
capitalLoss: Int,
hoursPerWeek: Int,
nativeCountry: String,
income: String
)

给定此 case 类,我必须创建一个伴随对象并定义以下函数:

打印
  • 数据:打印以下格式"$workclass - $occupation - $nativeCountry - $income">
  • apply:不带任何参数并返回类纳税人的实例,其中 Int 字段 = -1 和字符串字段 = "未知">

我已经尝试了以下内容,但它不起作用("预期的类或对象定义"(:

object Taxpayer{

def printData(c: Taxpayer) = {
println(s"${c.workclass} - ${c.occupation} - ${c.nativeCountry} - ${c.income}")
def apply(age: Int = -1, workclass: String = "unknown", education: "unknown", educationNum: Int = -1, maritalStatus: "unknown",
occupation: "unknown", relationship: "unknown", race: "unknown", sex: "unknown", capitalGain: Int = -1,
capitalLoss: Int = -1, hoursPerWeek: Int = -1, nativeCountry: "unknown", income: "unknown") = {
new Taxpayer(age, workclass, education, educationNum, maritalStatus, occupation, relationship,
race, sex, capitalGain, capitalLoss, hoursPerWeek, nativeCountry, income)
}
}
}

如何定义适用于数据集行的函数?提前谢谢你!:)

尝试

object Taxpayer{
def printData(c: Taxpayer) = {
println(s"${c.workclass} - ${c.occupation} - ${c.nativeCountry} - ${c.income}")
def apply(age: Int = -1, workclass: String = "unknown", education: String = "unknown", educationNum: Int = -1, maritalStatus: String = "unknown",
occupation: String = "unknown", relationship: String = "unknown", race: String = "unknown", sex: String = "unknown", capitalGain: Int = -1,
capitalLoss: Int = -1, hoursPerWeek: Int = -1, nativeCountry: String = "unknown", income: String = "unknown") = {
new Taxpayer(age, workclass, education, educationNum, maritalStatus, occupation, relationship,
race, sex, capitalGain, capitalLoss, hoursPerWeek, nativeCountry, income)
}
}
}

它在 2.13.2 https://scastie.scala-lang.org/3zq3SDzVTOuHtpgC6nyPIA 中编译

如果要使用默认值声明方法参数,则应像education: String = "unknown".当你写education: "unknown"时,你会做一些不同的事情(你声明没有默认值的单例类型的参数(。

相关内容

  • 没有找到相关文章

最新更新