Skip to main content

string Syntax

EmptyString ++ EmptyString

Problem without string syntax

To concatenate two or more NonEmptyStrings, you need to do something like this.

import eu.timepit.refined.types.string.NonEmptyString

val a = NonEmptyString("aaa")
// a: NonEmptyString = aaa
val b = NonEmptyString("bbb")
// b: NonEmptyString = bbb
NonEmptyString.unsafeFrom(a.value + b.value)
// res1: NonEmptyString = aaabbb

val hello = NonEmptyString("Hello")
// hello: NonEmptyString = Hello
val space = NonEmptyString(" ")
// space: NonEmptyString =
val world = NonEmptyString("world")
// world: NonEmptyString = world
NonEmptyString.unsafeFrom(hello.value + space.value + world.value)
// res2: NonEmptyString = Hello world

import eu.timepit.refined.auto._
NonEmptyString("A") + NonEmptyString("B") // This works but it returns String not NonEmptyString
// res3: String = "AB"

With string syntax

If you use string syntax from extras, you can just do

import eu.timepit.refined.types.string.NonEmptyString
import extras.refinement.syntax.string._

val a = NonEmptyString("aaa")
// a: NonEmptyString = aaa
val b = NonEmptyString("bbb")
// b: NonEmptyString = bbb
a ++ b
// res5: NonEmptyString = aaabbb

val hello = NonEmptyString("Hello")
// hello: NonEmptyString = Hello
val space = NonEmptyString(" ")
// space: NonEmptyString =
val world = NonEmptyString("world")
// world: NonEmptyString = world
hello ++ space ++ world
// res6: NonEmptyString = Hello world

More examples

import eu.timepit.refined.types.string.NonEmptyString
import extras.refinement.syntax.string._

NonEmptyString("abc") ++ NonEmptyString("def")
// res8: NonEmptyString = abcdef

val givenName = NonEmptyString("Kevin")
// givenName: NonEmptyString = Kevin
val surname = NonEmptyString("Lee")
// surname: NonEmptyString = Lee
val fullName = givenName ++ NonEmptyString(" ") ++ surname
// fullName: NonEmptyString = Kevin Lee