Home > Software engineering >  Scala: for-comprehension for chain of operations
Scala: for-comprehension for chain of operations

Time:11-23

I have a task to transform the following code-block:

  val instance = instanceFactory.create
  val result = instance.ackForResult

to for-comprehension expression.

As for-comprehension leans on enumeration of elements, I tried to get around it with wrapper class:

case class InstanceFactoryWrapper(value:InstanceFactory) {   
     def map(f: InstanceFactory => Instance): Instance
    = value.create()
 }

where map-method must handle only one element and return a single result: Instance

I tested this approach with this expression:

 for {
     mediationApi <- InstanceFactoryWrapper(instanceFactoryWrapper)
}

But it does't work: IDEA recommends me to use foreach in this part. But "foreach" doesn't return anything, as opposed to map.

What am I doing wrong?

CodePudding user response:

Simply put when working with List\Option\Either or other lang types comprehensions are useful to transform nested map\flatMap\withFilter into sequences.

Use custom classes in for-comprehension

But what about your own classes or other 3rd party ones?

You need to implement monadic operations in order to use them in for-comprehensions.
The bare minimum: map and flatMap.

Take the following example with a custom Config class:

case class Config[T](content: T) {

  def flatMap[S](f: T => Config[S]): Config[S] =
    f(content)

  def map[S](f: T => S): Config[S] =
    this.copy(content = f(content))
}

for {
  first  <- Config("..")
  _      =  println("Going through a test")
  second <- Config(first   "..")
  third  <- Config(second   "..")
} yield third

This is how you enable for-comprehension.

  • Related