[英]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
接受从String
到Unit
的函数,但是您要将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.