2016-02-05 95 views
0

這裏我試圖用隱式的方法調用一個函數。嘗試刪除儘可能多的鍋爐板代碼儘可能調用函數中使用:未調用Scala方法

("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 

這將調用F1與commandAndFunc。
您只需定義一個命令和函數的元組。爲什麼要調用f1?
編譯器/程序應該如何知道,如果它是對f1的調用或僅僅是Tuple2[Command,() => Unit]類型的元組聲明?
使用隱式,您可以在不顯式寫入參數的情況下移交參數,也可以將隱式對象轉換。你不能讓編譯器神奇地知道你想要調用什麼。

+0

請參閱更新,您的代碼不能編譯? –

+0

編輯它,'commandAndFunc'的類型是錯誤的,只是複製你的代碼 –

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()