How to compare two strings at the type level?

Two (singleton type) ints can be compared at the type level using e.g.<.

There doesn’t seem to be any similar definition in scala.compiletime.ops.string. The closest seems to be CharAt, but unfortunately, the latter returns a Char, for which there are no compile-time operations, unlike for Int and Long.

Am I missing something, or is there no way to compare chars/strings alphabetically at the type level? I doubt a match type with 65,536 cases would even compile…

type StringsAreEqualA[S1 <: String, S2 <: String] =
  compiletime.ops.any.==[S1, S2]

type StringsAreEqualB[S1 <: String, S2 <: String] <: Boolean = S1 match
  case S2 => true
  case _ => false

type X1A = StringsAreEqualA["lol", "lol"]
type X2A = StringsAreEqualA["lol", "wat"]
type X1B = StringsAreEqualB["lol", "lol"]
type X2B = StringsAreEqualB["lol", "wat"]

val x1a = compiletime.constValue[X1A]
val x2a = compiletime.constValue[X2A]
val x1b = compiletime.constValue[X1B]
val x2b = compiletime.constValue[X2B]

println(x1a) // prints true
println(x2a) // prints false
println(x1b) // prints true
println(x2b) // prints false

does that answer your problem?


Thanks! Sorry, I should have specified that I used the word “comparison” as in comparison sort. I would like to be able to sort strings at the type level.

do you need all possible char values? :slight_smile: maybe a short whitelist of characters would suffice?

i’ve played a bit with compile-time ops and match types, but i think there’s no way to convert a Char to its numeric (code point?) value, i.e. the Char can only be converted back to string, but not int, long or whatever else. without such conversions built into compiler, you would need to make your 65536 cases long conversion code yourself.

1 Like

A possible sidebar: Should there be a type-level standard library with this sort of thing? Would that make sense? (Does it already exist?)

@Bersier showed me how to make integers (and exponents) for type-safe measured units in , which was a huge help. (I needed 32-bit Floats, Ints, and ratios, so had to roll my own instead of just using Stephane’s.) I was astounded that I needed to define each integer myself.

Are there enough common parts to rate a standard library?

1 Like

That’s what I ended up doing :stuck_out_tongue:

1 Like

There is scala.compiletime (ops). However, it feels rather incomplete at this time; see

Nice! Thanks.

I wonder how efficient the compiler processes that? I think I’ll try making that into a stress test.

1 Like