blue-sky
blue-sky

Reputation: 53806

Why this error : type mismatch; found : Unit required: String => Unit

Below code :

object gen {
  println("Welcome to the Scala worksheet")

  case class CS(funToRun: String => Unit)

  val l: List[CS] = List(

    CS(open("filePath"))

    )

  def open(path: String): Unit = {
    java.awt.Desktop.getDesktop.open(new java.io.File(path))
  }
}

causes compiler error :

type mismatch; found : Unit required: String => Unit

But my open function is of of type String => Unit and param type of funToRun is String => Unit ?

Upvotes: 0

Views: 3429

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

CS accepts a function from String to Unit, but you're passing to it the result of open, which is Unit.

If you want to pass it open as a function instead, you need to do:

CS(open)

although without knowing what you're trying to achieve, it's impossibile to provide a sensible solution.

A possible alternative for performing the open action at a later time

case class CS(funToRun: () => Unit) // the function is not taking parameters any longer
val cs = CS(() => open("filePath")) // 'open' is not performed here
cs.funToRun() // 'open' is performed here

This way the open function is not evaluated when passed to the CS constructor.

Upvotes: 4

Related Questions