0

Imagine a union in thrift like:

union MyUnion {
  1. bool myBool
  2. i64 myLong
  3. double myDouble
}(persisted='true')

What I'd like to do is something like this in Scala:

case class MyClass(
  myString: String,
  myUnionType: ???
)

Then, I'd like to instantiate this class like:

import ...{thriftscala => thrift}

val myClass = MyClass("cool", thrift.MyUnion.MyBool)
val myOtherClass = MyClass("wow", thrift.MyUnion.MyLong)

Note that I am not instantiating MyBool or MyLong, I just want to pass them as "types". I.e., I am not doing:

val myClass = MyClass("cool", thrift.MyUnion.MyBool(_))

I'm curious if there is a way to do this using the thrift-generated Scala.

user451151
  • 406
  • 2
  • 10

1 Answers1

0

You can use an ADT like this :

scala> sealed trait MyUnion
defined trait

MyUnion

This is your base class and then extends with case object :

scala> case object  MyBool extends MyUnion
defined object MyBool

scala> case object MyDouble extends MyUnion
defined object MyDouble

scala> case object MyLong extends MyUnion
defined object MyLong

scala> case class MyClass(str : String, union : MyUnion)
defined class MyClass

How use it :

scala> MyClass("cool", MyBool)
res0: MyClass = MyClass(cool,MyBool)
alifirat
  • 2,899
  • 1
  • 17
  • 33
  • Thanks for taking a look. This is actually the way I'm currently handling it. The problem, however, is that now, in order to add a new "type" to MyBool, one needs to add it to both thrift *and* Scala. What I'm trying to do is leverage the thrift-generated Scala so I only have to add the type to the thrift file, without needing to maintain a separate trait. – user451151 Mar 21 '17 at 16:35
  • There isn't _really_ a way to do this because of the way the code is generated. You could implement a trait as @alifirat suggested, or you could implement a type class to handle union values for you. Either way though, you're going to have to implement _something_ if you change your thrift unions. – Charles Apr 22 '17 at 08:02