Fancy strings in Scala 3

PHOTO EMBED

Mon Apr 25 2022 20:05:41 GMT+0000 (Coordinated Universal Time)

Saved by @joel113 #scala

import scala.compiletime.{error, requireConst}

opaque type NonEmptyString = String

object NonEmptyString:
  def apply(s: String): Option[NonEmptyString] = 
    if s.isEmpty then None else Some(s)

  inline def from(inline s: String): NonEmptyString =
    requireConst(s)
    inline if s == "" then error("got an empty string") else s

  given Conversion[NonEmptyString, String] with
    inline def apply(nes: NonEmptyString): String = nes  
content_copyCOPY

https://softwaremill.com/fancy-strings-in-scala-3/