简体   繁体   English

将Option [String]拆分为(Option [String],Option [String])

[英]Split an Option[String] into (Option[String], Option[String])

For a normal String I am be able to do like this: 对于普通的String,我可以这样做:

val str = "asdzxc"
val (first, second) = str.splitAt(3) // splits into ("asd", "zxc")

I'd like to be able to do a similar thing for an Option[String] : 我希望能够对Option[String]做类似的事情:

val optionalString: Option[String] = getOptionalString(...)
val (firstOption, secondOption) = ???

So that the types of firstOption and secondOption would be Option[String] . 这样firstOptionsecondOption的类型将是Option[String] I know I can do like this: 我知道我可以这样:

optionalString.map(_.splitAt(3))

which returns me an Option[(String, String)] but that is not what I'm looking for. 返回我一个Option[(String, String)]但这不是我想要的。 Any ideas? 有任何想法吗?

You can either use a fold: 您可以使用折叠:

optionalString.map(_.splitAt(3)).fold((None: Option[String], None: Option[String])) { case (a, b) => (Some(a), Some(b)) }

Or pattern matching (possibly a bit clearer since it doesn't need the explicit type parameters): 或模式匹配(由于不需要显式类型参数,因此可能更清晰一点):

optionalString.map(_.splitAt(3)) match {
  case None => (None,None)
  case Some((a,b)) => (Some(a), Some(b))
}       

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM