Geo Geo - 1 month ago 7x
Scala Question

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?


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.) That is:

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.