Search code examples
scalatype-safety

How to pass around string values type-safely?


E.g.:

def updateAsinRecords(asins:Seq[String], recordType:String)

Above method takes a Seq of ASINs and a record type. Both have type of String. There are also other values that are passed around with type String in the application. Needless to say, this being Scala, I'd like to use the type system to my advantage. How to pass around string values in a type safe manner (like below)?

def updateAsinRecords(asins:Seq[ASIN], recordType:RecordType)
                                ^                 ^

I can imagine, having something like this:

trait ASIN { val value:String }

but I'm wondering if there's a better approach...


Solution

  • There is an excellent bit of new Scala functionality know as Value Classes and Universal Traits. They impose no runtime overhead but you can use them to work in a type safe manner:

    class AnsiString(val inner: String) extends AnyVal
    class Record(val inner: String) extends AnyVal
    
    def updateAnsiRecords(ansi: Seq[AnsiString], record: Record)
    

    They were created specifically for this purpose.