2017-05-07 56 views
0

我挺有用的打字稿的功能與-PARAM-名稱作爲功能PARAMS:scala命名參數在函數作爲參數?

function doHello(
    helloFunc: (lastName: string, firstName: string) => void, 
    ... 
) { ... } 

這裏,helloFunc描述了 '命名爲' PARAMS(姓氏,名字)

功能-AS-PARAM

但我只能找到不PARAM-名的例子,比如:

case class HelloWoot(
    helloFunc: (String, String) => Unit, 
    ... 
) 

其省略了約helloFunc簽名的一些信息。

那麼,我如何獲得以下代碼在Scala中編譯?

case class HelloWoot(
    helloFunc: (lastName: String, firstName: String) => Unit, 
    // Error 
) 

回答

2

無法在高階函數中提供命名參數。如果你擔心人們混淆了字符串參數,你可以引入這樣的新類型:

// New object with firstName and lastName 
case class NamesObject(firstName: String, lastName: String) 

// Higher order function now takes the new type as input 
case class HelloWoot(helloFunc: (NamesObject) => Unit) 

// You can now safely access the correct variable without having to rely on their order in the Tuple2 
HelloWoot(a => println(a.firstName, a.lastName)) 
+0

did scala禁用在高階函數中通過設計提供命名參數?或者這是scala的一個'bug'還是缺少的特性? –

+0

我懷疑它,因爲你只是定義了參數的類型,在這種情況下,該類型恰好是一個函數,是類型'(String,String)=> Unit' – Tyler

+0

我想這可能是scala的原因這樣做......但似乎省略了太多關於代碼的信息... 希望斯卡拉人會更關心變量名...使用像'm'這樣的名字和寫一本書說'猿是一個以m開頭的詞,所以這必須是幺半物!'是完全瘋狂:( –