How to specify a shapeless singleton type ahead of time

Viewed 272

I'd like to construct a type like LimitedString[Limit] where Limit is a type representation of the maximum length of the string.

It would work along the lines of

class LimitedString[Limit] [private](val s: String)
object LimitedString {
  private def getLimit[Limit]: Int = ??? // turn `Limit` type into a value
  def truncate[Limit](s: String) = new LimitedString[Limit](s take getLimit)
  def get[Limit](s: String) = 
    if(s.length < getLimit) Some(new LimitedString[Limit](s))
    else None
}

type Str100 = LimitedString[100] // obviously this won't work
def someLibraryMethod(s: Str100) = { ... }

What I can't figure out is how to actually type (as in keyboard) the type (as in compilation) for Limit.

I started looking into Shapeless's singleton types and found that you can say

100.narrow
// res1: Int(100) = 100

But if I try to use Int(100) as the type, I get errors.

val x: Int(100) = 100
// error: ';' expected but '(' found.

Additionally, how would I implement something like def getLimit[Limit]: Int?

1 Answers
Related