How to encode it in idiomatic Scala?

Suppose I want to write a function def pair(s:String):Option[(String, String)]to convert a string to a key-value pair in Scala. The line should look like "<key>:<value>".

How do you fix the solution below?

def pair (s: String) = {
  val a = s.split (":"); if (a.length == 2) Some ((a (0) .trim, a (1) .trim)) else None
}
+4
source share
2 answers

The two approaches that I personally find are a bit nicer:

def pair(s: String) = s.split(":") match {
  case Array(k, v) => Some(k.trim -> v.trim)
  case _ => None
}

Or using Scala's handy regex extractors:

val Pair = """\s*([^\s:]+)\s*:\s*([^\s:]+)\s*""".r

def pair(s: String) = s match {
  case Pair(k, v) => Some(k -> v)
  case _ => None
}

But yes, yours is not so bad either.

+8
source

I will remove the semicolon and make it two lines. Otherwise, this is an absolutely wonderful functional code.

:

def pair(s:String) = 
  s.split(":") match {
    case Array(a, b) => Some(a, b)
    case _ => None
  } 

, , , if-else - , . , . , a(0), .

- , . , a(0) , . if, , , . .

, if-else. , . , .

+4

Source: https://habr.com/ru/post/1526544/


All Articles