是否有与 Python 列表解包(又名“*")运算符等效的 Scala 运算符? [英] Is there a Scala equivalent of the Python list unpack (a.k.a. "*") operator?

查看:65
本文介绍了是否有与 Python 列表解包(又名“*")运算符等效的 Scala 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我们有星号(或*"或解包")运算符,它允许我们解包列表以便于传递位置参数.例如:

In Python, we have the star (or "*" or "unpack") operator, that allows us to unpack a list for convenient use in passing positional arguments. For example:

range(3, 6)
args = [3, 6]
# invokes range(3, 6)
range(*args)

在这个特定的例子中,它并没有节省太多的输入,因为 range 只需要两个参数.但是你可以想象,如果 range 有更多的参数,或者如果 args 从输入源读取,从另一个函数返回等,那么这可能会派上用场.

In this particular example, it doesn't save much typing, since range only takes two arguments. But you can imagine that if there were more arguments to range, or if args was read from an input source, returned from another function, etc. then this could come in handy.

在 Scala 中,我一直无法找到等价物.考虑在 Scala 交互式会话中运行以下命令:

In Scala, I haven't been able to find an equivalent. Consider the following commands run in a Scala interactive session:

case class ThreeValues(one: String, two: String, three: String)

//works fine
val x = ThreeValues("1","2","3")

val argList = List("one","two","three")

//also works
val y = ThreeValues(argList(0), argList(1), argList(2))

//doesn't work, obviously
val z = ThreeValues(*argList)

除了val y中使用的方法外,还有更简洁的方法吗?

Is there a more concise way to do this besides the method used in val y?

推荐答案

函数也有类似的东西:tupled 它将一个接受 n 个参数的函数转换成一个接受一个 n 类型参数的函数-元组.

There is something similar for functiones: tupled It converts a function that takes n parameters into a function that takes one argument of type n-tuple.

查看此问题了解更多信息:scala 元组解包

See this question for more information: scala tuple unpacking

这种用于数组的方法没有多大意义,因为它只适用于具有多个相同类型参数的函数.

Such a method for arrays wouldn't make much sense, because it would only work with functions with multiple arguments of same type.

这篇关于是否有与 Python 列表解包(又名“*")运算符等效的 Scala 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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