computereasy computereasy - 13 days ago 6
Scala Question

Define OCaml-style type variants in Scala

I am new to

Scala
but have some experience in using
OCaml
and some other ML family functional programming languages.

I am wondering how could I define the
OCaml
style type variants? For example,

type fruit = Apple | Orange | Strawberry
let analysis f =
match f with
| Apple -> ...
| Orange -> ...
| Strawberry -> ...


I am sorry if this question is too naive.. Hope someone can help me on that.

Answer

I don't know OCaml, but it looks like you're trying to do something like this.

sealed abstract class Fruit
class Apple extends Fruit
class Orange extends Fruit
class Strawberry extends Fruit

def mixFruit(f: Fruit) = f match {
  case a: Apple =>      // do something with a
  case o: Orange =>     // do something with o
  case s: Strawberry => // do something with s
}
Comments