Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching or Map Monads

Tags:

scala

I was wondering what do you guys think is more idiomatic and better in terms of performance.

Over a monad of type Option or Try, use pattern matching or map and getOrElse in case you want to control the side effect.

So what do you think is better this:

maybeConnectTimeout
  .map(connectTimeout => session.connect(connectTimeout))
  .getOrElse(session.connect())

Or this

maybeConnectTimeout match {
  case Some(connectTimeout) => session.connect(connectTimeout)
  case None => session.connect()
}
like image 360
paul Avatar asked Sep 18 '21 21:09

paul


People also ask

What is pattern matching in ML?

A special feature of languages in the ML family is pattern matching. It allows simple access to the components of complex data structures. A function definition most often corresponds to pattern matching over one of its parameters, allowing the function to be defined by cases.

What is the use of Scala pattern matching?

Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.


Video Answer


1 Answers

what ... is ... better in terms of performance.

According to odersky pattern match

I am surprised that the pattern match gets so little love here. Not only is it by far the fastest (probably at least 10 times as fast as the alternatives), it is also the clearest.

like image 50
Mario Galic Avatar answered Oct 17 '22 21:10

Mario Galic