2017-05-07 57 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开头的词,所以这必须是幺半物!'是完全疯狂:( –