Getting "error: type mismatch; found : Unit required: () => Unit" on callback
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.
The difference is that this line:
timer(println(frenchDate))
is trying to call println(frenchDate)
and use the return value (which is Unit
) as the callback to pass to timer
. You probably want:
timer(() => println(frenchDate))
or possibly
timer(() => { println(frenchDate) })
(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:
timer { () => println(frenchDate) }
精彩评论