如何在 Scala 中为未指定数量的参数函数创建函数?

编程入门 行业动态 更新时间:2024-10-23 10:28:19
本文介绍了如何在 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 中为未指定数量的参数函数创建函数?

本文发布于:2023-11-01 02:21:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1547974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   中为   数量   参数   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!