Reputation: 11297
I have some code that converts the elements of sequences with different functions like that:
someSequence map converterFunction
However, sometimes I have not a sequence but a single value that is to be passed to the function. For consistency with the other lines I'd like to write it like that
someValue applyTo converterFunction
So in a way it is like mapping a single value. Of course I can just call the function with the value, I'm just wondering if it is possible to write it similar to the way I proposed.
Upvotes: 0
Views: 105
Reputation: 23788
I agree with ChrisK that this idea doesn't sound as a good one to me in terms of code readability but if you really want it, you can do it using something like this:
implicit final class MapAnyOp[T](val value: T) extends AnyVal {
def map[R](f: T => R) = f(value)
}
def convert(v: Int): String = Integer.toHexString(v)
println(List(123, 234, 345) map convert)
println(123 map convert)
Upvotes: 2
Reputation: 448
You could wrap it in a Seq:
Seq(someValue) map converterFunction
If someValue is a custom type/class, you can define an operator that will do that for you instead of having this explicit wrapping.
someValue.seq map converterFunction
Upvotes: 1