scala在function-as-params中命名参数?

时间:2017-05-07 04:38:33

标签: scala

我很习惯使用Typescript的函数-param-name作为函数参数:

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

这里,helloFunc描述了一个带有'named'参数的函数as-param(lastName,firstName)

但我只能找到没有param-names的例子,例如:

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

省略了一些关于helloFunc签名的信息。

那么,如何在Scala中编译以下代码?

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

1 个答案:

答案 0 :(得分:2)

无法在更高阶函数中提供命名参数。如果你担心人们混合了String参数,你可以引入一个像这样的新类型:

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