So I’m getting into Scala and I have a question if what I want to do is possible, or if there’s a better way.
I want to be able to take as a parameter a Map whose keys are either strings, or 0-args function returning a string. So for example
def main(args: List[String]){
f = F(
Map(
"key" -> "value",
"key2" ->(()=> {"valule2"})
)
)
println(f("key"))
}
case class F(arg: Map[String, ???]){
def apply(s: String): String = {arg(s)}
}
This obviously doesn’t compile. Is there any way to do this?
In this case you can use scala.Either
Update
You can hide implementation from caller using something like this.
The actual type of
Function0is eliminated due type erasure, but it can be verified withManifestUpdate2
As @Submonoid rightly corrected me in the comments below, there is much simpler way of dealing with
Either.