scala找到Unit需要Unit.type

Geo*_*Geo 2 scala

我有以下内容:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

但这无法编译错误:

Error:(8, 21) type mismatch;
 found   : Unit
 required: Unit.type
      (s:String) => ()
Run Code Online (Sandbox Code Playgroud)

为什么第二类的覆盖不是有效的?我怎么能让它工作?

Sea*_*ira 5

问题是(s:String) => Unit返回Unit.type- 而是将其更改为(s:String) => ()(或者如果您不想Function1[String, Unit]从方法返回,则更改为方法.)

换一种方式:

def doSomething = (s:String) => Unit
Run Code Online (Sandbox Code Playgroud)

是真的:

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

虽然你可能想要的是:

def doSomething: (String) => Unit =
  // A function that takes a string and returns Unit
  (s: String) => ()
Run Code Online (Sandbox Code Playgroud)

或者可能:

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