How does a monkey pay new management structures in Scala?

Is it possible to defuse a new management structure in Scala? Basically, I want to define a couple of management structures, for example, the following with the exception of the method, and have them available anywhere in my project.

def unless(condition: => Boolean)(body: => Unit):Unit = if(!condition) body
+5
source share
2 answers

You cannot patch a monkey that modifies objects that already exist. However, in most cases, you can write an implicit conversion that acts the same way (and possibly more safely).

First of all, when writing, unlessyou do not need to be a method of each class. Just paste it into some object and import.

object Utility {
  def unless(condition: => Boolean)(body: => Unit):Unit = if(!condition) body
}

import Utility._

, . ,

option.map(x => f(x)).getOrElse(default)

:

option.fold(default)(x => f(x))

, Option . , :

class OptionWrapper[A](o: Option[A]) {
  def fold[Z](default: => Z)(action: A => Z) = o.map(action).getOrElse(default)
}
implicit def option_has_utility[A](o: Option[A]) = new OptionWrapper(o)

( " " ). fold to my heart content, , fold, , fold , - - fold. , , fold .

+11

( , Scala!), package object.

+2

All Articles