如何在 Scala 中为未指定数量的参数函数创建函数? [英] How can I make function for unspecified number of arguments function In Scala?

查看:36
本文介绍了如何在 Scala 中为未指定数量的参数函数创建函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为未指定数量的函数参数创建一些函数

I want to make some function for unspecified number of arguments of function

例如

scala> def test(fx: (String*) => Boolean, arg: String*): Boolean = fx(arg: _*)
test: (fx: String* => Boolean, arg: String*)Boolean

scala> def AA(arg1: String, arg2: String) :Boolean = {
       println ("Arg1 : " + arg1 + " Arg2 : " + arg2)
       true}
AA: (arg1: String, arg2: String)Boolean

scala> test(AA,"ASDF","BBBB")
<console>:10: error: type mismatch;
 found   : (String, String) => Boolean
 required: String* => Boolean
            test(AA,"ASDF","BBBB")
                  ^

我该如何解决这个问题??

How can I solve this problem??

推荐答案

这可以通过使用 shapeless 和 ProductArgs 以及类似于我的 回答另一个问题.

This could be done using shapeless with ProductArgs and something similar to my answer to another question.

import shapeless.{HList, ProductArgs}
import shapeless.ops.hlist.IsHCons
import shapeless.ops.function.FnToProduct
import shapeless.syntax.std.function._

object test extends ProductArgs {
  def applyProduct[L <: HList, NarrowArgs <: HList, Args <: HList, F, R](
    l: L
  )(implicit 
    ihc: IsHCons.Aux[L, F, NarrowArgs],
    ftp: FnToProduct.Aux[F, Args => R],
    ev: NarrowArgs <:< Args
  ): R = {
    val (func, args) = (l.head, l.tail)
    func.toProduct(args)
  }
}

您可以用作:

def aa(s1: String) = s1.length
def bb(s1: String, s2: String) = s1 * s2.length

test(aa _, "foo")         // Int = 3
test(bb _, "foo", "bar")  // String = foofoofoo
// test(aa _, "foo", "bar") doesn't compile

扩展 ProductArgs 转换或 test(aa _, "foo")(实际上是 test.apply(aa _, "foo")code>) 到 test.applyProduct((aa _) :: "foo" :: HNil).在 applyProduct 中,我们检查 HList 是否包含一个函数和有效参数.

Extending ProductArgs transforms or test(aa _, "foo") (which is actually test.apply(aa _, "foo")) to test.applyProduct((aa _) :: "foo" :: HNil). In applyProduct we check that the HList consists of a function and valid arguments.

我们不需要 NarrowArgs <:<参数,但ProductArgs 似乎给出与 SingletonProductArgs.

这篇关于如何在 Scala 中为未指定数量的参数函数创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆