我试图为spark sql注册一些udfs(用户定义的函数),当我尝试编译时,我得到以下代码的类型不匹配错误:
csc.udf.register("DATEADD", (datePart: String, number: Int, date: Timestamp) => {
val time: Calendar = Calendar.getInstance
datePart match {
case "Y" => time.add(Calendar.YEAR, number)
case "M" => time.add(Calendar.MONTH, number)
case "D" => time.add(Calendar.DATE, number)
case "h" => time.add(Calendar.HOUR, number)
case "m" => time.add(Calendar.MINUTE, number)
case "s" => time.add(Calendar.SECOND, number)
case _ => 0
}
}: Int)
以下是我遇到的错误:
[error] /vagrant/SQLJob/src/main/scala/sqljob/context/CassandraSQLContextFactory.scala:111: type mismatch;
[error] found : Unit
[error] required: Int
[error] case "Y" => time.add(Calendar.YEAR: Int, number)
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 7 s, completed Jul 2, 2015 4:19:29 PM
Calendar类来自java.util.Calendar
来自java.sql.Timestamp
的时间戳答案 0 :(得分:4)
您的函数类型为(String, Int, Timestamp) => Int
,因此它应返回Int
。
Calendar.add
是最后一个表达式,因此由函数返回,但其返回类型为Unit
而不是Int
。这就是为什么你收到错误告诉你的原因。
答案 1 :(得分:1)
Calendar.add
实际上会改变对象,并在Scala中返回void
(Unit
)。您应该在time
上调用其中一个访问器方法来检索它的数字表示。