问题
In Ocaml it is possible to define something like this:
type univ = I of int | F of float | S of string ;;
In order to create objects with like this:
let pol_list = [I 3; F 4.3; S "potato"; I 4];;
And then do pattern matching to extract a certain property (Either value or length depending on the case) like this:
let get_value val =
match val with
| I v -> v
| F v -> (int_of_float v)
| S s -> (String.length s)
How would this be done in Scala? If not possible, is there another similar alternative?
回答1:
I don't know OCaml, but it seems univ is an Algebraic Data Type, which you could model in Scala with a sealed trait and some case classes (which is more verbose than in OCaml) :
sealed trait Univ extends Product with Serializable
case class I(i: Int) extends Univ
case class F(f: Float) extends Univ
case class S(s: String) extends Univ
val polList = List(I(3), F(4.3f), S("potato"), I(4))
def getValue(v: Univ): Int = v match {
case I(i) => i
case F(f) => f.toInt
case S(s) => s.length
}
polList.map(getValue) // List[Int] = List(3, 4, 6, 4)
回答2:
Maybe something like that:
val mix = List(1, "foo", 4.5)
val normalized = for (e <- mix) yield {
e match {
case s: String => s.length
case i: Int => i
case d: Double => d.toInt
}
}
println(normalized)
List(1, 3, 4)
来源:https://stackoverflow.com/questions/33384189/type-to-capture-either-integer-float-or-a-string-value-and-then-do-pattern-matc