简体   繁体   English

在Scala中表达单个元素的可迭代性的最惯用的方法是什么?

[英]What's the most idiomatic way to express an iterable of a single element in Scala?

So far when I need to pass around an Iterable that consists of just one element, I pass a Some value; 到目前为止,当我需要传递仅包含一个元素的Iterable ,我传递了Some值; but that requires an implicit conversion. 但这需要隐式转换。

In Java I would use java.util.Collections.singleton , and I guess there's something equivalent in Scala that better fits this use case. 在Java中,我将使用java.util.Collections.singleton ,而且我猜Scala中有一个等效项可以更好地适合此用例。

Iterable(x) ,就像获取单个元素的Seq ,您可以编写Seq(x)List(x)等。

After taking a look to the implementation of the apply methods (constructors) of the collections ( Iterable , Seq , List ) that could fit the bill, they take varargs which require extra wrapping the object in an array and then looping over it or calling another method. 在研究了可能符合要求的集合( IterableSeqList )的apply方法(构造函数)的实现之后,他们采用了varargs,这需要将对象额外包装在数组中,然后在其上循环或调用另一个方法。

So I think I'm going to stick with consing the object like x :: Nil ; 所以,我想我会坚持使用consing像对象x :: Nil ; that looks like the most lightweight way to achieve it and it's explicit that you are making a collection. 这看起来是实现它的最轻量的方法,很明显,您正在制作一个集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Scala中最常用的方式是在Seq上将模式匹配保持转换为字符串的枚举值吗? - What's the most idiomatic way in Scala to pattern match on a Seq holding enum values converted to strings? 在 Scala 中,命名与 ORM 类等效的 case 类的最惯用方法是什么? - In Scala, what's the most idiomatic way to name the case class equivalent of an ORM class? Scala 按分隔符拆分列表的惯用方法是什么? - What's Scala's idiomatic way to split a List by separator? 什么是从不可变列表中“删除”一个元素的惯用Scala方法? - What is an idiomatic Scala way to “remove” one element from an immutable List? 鞍架:计算NaN值最惯用的方法是什么? - Saddle Frame: What's the most idiomatic way to count NaN values? 在Scala中将多个函数定义为相同类型的惯用方式是什么? - What's the idiomatic way to define multiple functions as the same type in Scala? 在 Scala 中,在功能上遍历和更新数据结构的惯用方法是什么? - What's an idiomatic way to traverse and update data structures functionally in Scala? 在Scala中执行map / getOrElse返回单位的惯用方式是什么? - What's the idiomatic way to do a map/getOrElse returning Unit in Scala? 更加惯用(monadic?)方式来表达这个Scala - More idiomatic (monadic?) way to express this Scala Scala:给定一个scala.xml.Node,获取第二个(或第n个)子元素的最有效方法是什么? - Scala: Given a scala.xml.Node, what's the most efficient way of getting the second (or n-th) child element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM