Artur Eshenbrener
Artur Eshenbrener

Reputation: 2020

Scala. Convert any val to other value in functional style

I think that it could be useful to have method convertTo or other name in Any class, which will get function, which converts it to other val. Signature of this method could be like this (example A):

def convertTo[T](convertor: this.type => T) : T = convertor(this)

With this method developer can simply convert one object to other using convertor. In real-life world it can be used for conversion from List[Future[T]] to Future[List[T]] with this code (example B):

/* long code, which constructs List[Future[T]] */ convertTo { list => Future.sequence(list) }

instead of this (example C):

Future.sequence( /* long code, which constructs List[Future[T]] */ )

I think that code in example B is much more functional-style, that code in example C. So, I have a two questions:

  1. Is it fit to functional-style coding paradigm?
  2. Is there any already existed library for Scala, which provides something like this?

Upvotes: 0

Views: 117

Answers (1)

lmm
lmm

Reputation: 17431

  1. "Functional" means many things to many people. I think this style can (sometimes) make code more readable as it makes the code correspond more closely to the data flow, but I wouldn't describe it as "more functional".

  2. How about scalaz |>?, e.g.

    [code that constructs List[Future[T]]]] |> Future.sequence

Note that this works with any function, it's not necessarily a "convertTo".

Upvotes: 1

Related Questions