Geo
Geo

Reputation: 96957

scala found Unit required Unit.type

I have the following:

object T {
  abstract class First {
    def doSomething= (s:String) => Unit
  }

  class Second extends First {
    override def doSomething = {
      (s:String) => ()
    }
  }

  def main(args: Array[String]): Unit = {
    new Second().doSomething
  }
}

but this fails to compile with the error:

Error:(8, 21) type mismatch;
 found   : Unit
 required: Unit.type
      (s:String) => ()

Why isn't the override from class Second valid? How could I make it work?

Upvotes: 2

Views: 1678

Answers (3)

BdEngineer
BdEngineer

Reputation: 3209

' trait Processor0 {
  def process = (x:String) => () 
}
case class Processor2() extends Processor0 {
  override def process = (x:String) =>  println("Processor2 x :" + x)
}
case class Processor3() extends Processor0 {
  override def process = (x:String) =>  println("Processor3 x :" + x)
}
object DemoProc2 {
  def main( args : Array[String]):Unit ={
  val s:String = "yes"
 val myFuncs: Map[String,(String) => () ]=  Map(  //Error  1. '=>' expected but ']' found.  2.identifier expected but ';' found.
           "string2" -> (() => ProcessorTwo().process(s)),
          "string3" -> (() => ProcessorThree().process(s))
        )
   myFuncs.values.foreach(v => v());
  }
} '

Upvotes: -1

Sean Vieira
Sean Vieira

Reputation: 160063

The problem is that (s:String) => Unit is returning Unit.type - instead change it to (s:String) => () (or to a method if you didn't mean to be returning Function1[String, Unit] from your method.)

To put it another way:

def doSomething = (s:String) => Unit

is really:

def doSomething: (String) => Unit.type =
  // A function that takes a string and returns the companion type of Unit
  (s: String) => Unit

While what you probably wanted was:

def doSomething: (String) => Unit =
  // A function that takes a string and returns Unit
  (s: String) => ()

Or maybe:

def doSomething(s: String): Unit
// An abstract method that takes a string and returns nothing.

Upvotes: 5

manojlds
manojlds

Reputation: 301527

(s:String) => Unit returns Unit.type ie it returns the type rather than a value of that type. You want to do (s:String) => (), which will return a value, whose type is Unit.

Upvotes: 2

Related Questions