这里我尝试使用隐式'来尝试调用函数。尝试使用以下方法删除尽可能多的锅炉板代码调用函数:
("a" and "j", {
println("Hello");
})
但这不会调用f1
如何通过调用
调用函数f1
("a" and "j", {
println("Hello");
})
完整代码:
object First extends App {
case class Commands(val list: List[String]) {
def and(that: String) = Commands(that :: list)
}
implicit def l(cmd: String) = Commands(cmd :: Nil)
implicit def f1(implicit d: (Commands, () => Unit)): Unit = {
val launchCommand = d._1.list.reverse.mkString("") + "::"
println(launchCommand)
println("This method is not being invoked");
d._2()
}
("a" and "j", {
println("Hello");
})
}
更新:
object First extends App {
case class Commands(val list: List[String]) {
def and(that: String) = Commands(that :: list)
}
implicit def l(cmd: String) = Commands(cmd :: Nil)
implicit def f1(implicit d: (Commands, () => Unit)): Unit = {
val launchCommand = d._1.list.reverse.mkString("") + "::"
println(launchCommand)
println("This method is not being invoked");
d._2()
}
implicit val commandAndFunc = ("a" and "j", {
println("Hello");
})
f1
}
f1
导致编译器错误:
Multiple markers at this line:
◾not enough arguments for method f1: (implicit d: (First.Commands, () ⇒ Unit))Unit. Unspecified value parameter d.
◾could not find implicit value for parameter d: (First.Commands, () ⇒ Unit)
答案 0 :(得分:2)
implicit val commandAndFunc: (Commands, () => Unit) = ("a" and "j", { () =>
println("Hello")
})
f1
这将使用commandAndFunc调用f1
您只需定义命令和函数的元组。为什么要调用f1?
编译器/程序应该如何知道,如果它是对f1的调用还是只是类型为Tuple2[Command,() => Unit]
的元组的声明?
使用隐式,您可以移交参数而无需将其显式化,也可以隐式转换对象。你不能让编译器神奇地知道你想要调用什么。
答案 1 :(得分:0)
另一种选择:
case class Commands(val list: List[String]) {
def and(that: String) = Commands(that :: list)
}
implicit def l(cmd: String) = Commands(cmd :: Nil)
implicit class f1(d: (Commands, () => Unit)) {
def exec(): Unit = {
val launchCommand = d._1.list.reverse.mkString("") + "::"
println(launchCommand)
println("This method is not being invoked");
d._2()
}
}
val b = ("a" and "j", () => println("Hello"))
b.exec()