简体   繁体   English

为什么出现此错误:类型不匹配; 找到:所需单位:字符串=>单位

[英]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 ? 但是我的打开函数的类型为String => Unit并且funToRun的参数类型为String => Unit

CS accepts a function from String to Unit , but you're passing to it the result of open , which is Unit . CS接受从StringUnit的函数,但是您要将open的结果传递给它,即Unit

If you want to pass it open as a function instead, you need to do: 如果要改为将其作为函数传递为open ,则需要执行以下操作:

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 在以后执行open操作的可能替代方法

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. 这样,当传递给CS构造函数时,就不会评估open函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:类型不匹配; 找到:Unit.type必需:Unit - error: type mismatch; found: Unit.type required: Unit 得到“错误:类型不匹配;发现:需要单位:()=>单位“回调 - Getting “error: type mismatch; found : Unit required: () => Unit” on callback Scala类型不匹配-找到:所需单位:Array [String] - Scala type mismatch - found: Unit required: Array[String] 找到:所需单位:for循环的List [Int]类型不匹配错误 - found : Unit required: List[Int] type mismatch error for for loop Eclipse编译错误-类型不匹配;找到:Scala中的单位必需为Int - Eclipse Compilation error - Type mismatch;found:Unit required Int in Scala 在我的 scala function 中,为什么会出现错误 - “类型不匹配;找到:所需单位:Int”? - In my scala function, why am I getting error - "type mismatch; found : Unit required: Int"? Scala:找到类型不匹配,需要单位:布尔值 - Scala: Type Mismatch found, Unit required: Boolean Scala:类型不匹配; found:需要的单位:布尔值 - Scala: type mismatch; found : Unit required: Boolean Scala - 找不到类型不匹配单位:必需数组[Int] - Scala - Type Mismatch Found Unit : required Array[Int] 平面图上发现类型不匹配的单位,必填Future [Customer] - Type mismatch found Unit, required Future[Customer] on flatmap
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM