收到“错误:类型不匹配”找到:所需单位:() =>单位”回调时
我刚刚开始学习 scala 教程,但遇到了障碍。我将几个示例合并在一起并收到错误,但不知道为什么。
import java.text.DateFormat._
import java.util.{Date, Locale}
object FrenchDate {
def main(args: Array[String]) {
timer(println(frenchDate))
}
def frenchDate():String = {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
df format now
}
def timer(callback: () => Unit) {
while(true) {callback(); Thread sleep 1000}
}
}
出现错误
error: type mismatch;
found : Unit
required: () => Unit
println(frenchDate)
在下面的代码运行时
import java.text.DateFormat._
import java.util.{Date, Locale}
object FrenchDate {
def main(args: Array[String]) {
timer(frenchDate)
}
def frenchDate() {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format now)
}
def timer(callback: () => Unit) {
while(true) {callback(); Thread sleep 1000}
}
}
唯一的区别是日期在第二次的 frenchDate() 中打印出来,而在第一次的回调中返回并打印日期。
I am just starting out going through a tutorial on scala and have hit a block. I have merged together a couple of examples and am getting an error, but don't know why.
import java.text.DateFormat._
import java.util.{Date, Locale}
object FrenchDate {
def main(args: Array[String]) {
timer(println(frenchDate))
}
def frenchDate():String = {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
df format now
}
def timer(callback: () => Unit) {
while(true) {callback(); Thread sleep 1000}
}
}
Brings the error
error: type mismatch;
found : Unit
required: () => Unit
println(frenchDate)
while the below works
import java.text.DateFormat._
import java.util.{Date, Locale}
object FrenchDate {
def main(args: Array[String]) {
timer(frenchDate)
}
def frenchDate() {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format now)
}
def timer(callback: () => Unit) {
while(true) {callback(); Thread sleep 1000}
}
}
The only difference is that the date is printed out in frenchDate()
in the second once whereas it is returned and printed in the callback on the first.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不同之处在于,这一行:
尝试调用
println(frenchDate)
并使用返回值(即Unit
)作为回调传递给timer< /代码>。您可能想要:
或者可能
(我不是 Scala 开发人员,所以我不确定语法是否正确,但我对当前代码中的问题非常有信心:)
编辑:根据评论,这应该可行也可能更惯用:
The difference is that this line:
is trying to call
println(frenchDate)
and use the return value (which isUnit
) as the callback to pass totimer
. You probably want:or possibly
(I'm not a Scala dev, so I'm not sure of the right syntax, but I'm pretty confident about what's wrong in your current code :)
EDIT: According to comments, this should work too and may be more idiomatic: