Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 448
jaz9090 Avatar asked Feb 13 '26 19:02

jaz9090


1 Answers

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) }
like image 134
Jon Skeet Avatar answered Feb 16 '26 19:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!