[英]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. 在研究了可能符合要求的集合(
Iterable
, Seq
, List
)的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.