Scala:我可以将选项转换为可变参数吗?
我有一个 Option
:
val myOption: Option[Int] = fooBar()
和一个采用可变参数参数的方法:
def myMethod(a: String, b: Int*) = {...}
有什么方法可以将选项作为可变参数参数传递给该方法吗?即,如果选项是 Some(3)
则传递 3,如果是 None
则不传递任何内容。
尝试一下答案 scala:如何传递扩展列表作为 varargs 到方法中? 我尝试显式键入参数:
myMethod("xyz", myOption: _*)
但编译器抱怨它需要 Seq[Int]
。看来Option
没有实现Seq
并且没有predef隐式转换。
鉴于编译器需要一个 Seq
,我当然可以传递 myOption.toList: _*
,但是有更好的方法吗?
I have an Option
:
val myOption: Option[Int] = fooBar()
And a method that takes a varargs param:
def myMethod(a: String, b: Int*) = {...}
Is there any way to pass the option to the method as a varargs param? i.e. if the option is Some(3)
then pass 3, and if it is None
then pass nothing.
Experimenting with the answer to
scala: How to pass an expanded list as varargs into a method? I tried explicitly typing the argument:
myMethod("xyz", myOption: _*)
but the compiler complains that it requires a Seq[Int]
. It seems that Option
does not implement Seq
and there is no predef implicit conversion.
Given that the compiler wants a Seq
, I can of course pass myOption.toList: _*
, but is there a nicer way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)