简体   繁体   中英

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?
  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 |> ?, eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM