0

I can see a few benefits of creating a custom type over using a string for things like:

type UserId = String

def getUser(userId: UserId)...

versus:

def getUser(userId: String)...

It makes your code more readable, and I imagine if you ever need to change the type from a String to a Int it would make refactoring easier.

What other benefits are there?

cool breeze
  • 4,461
  • 5
  • 38
  • 67
  • 1
    It seems a little odd to call a type alias a "custom type"—it's just an alternative name. `case class UserId(value: String)` would be a custom type (and a much better idea in my opinion—either use `String` or use a case class, not a type alias). – Travis Brown Oct 05 '16 at 18:22

2 Answers2

3

While using type can improve readability in some cases, if you use it to create an alias it won't make your code safer or easier to refactor. Consider:

type A = String

def m(s: A) = s.length

m("12345") // It's "safe" to use String instead of A

If you want a wrapper so you don't pass e.g. user login where user name is expected (both strings), you can use a value class:

class UserName(val name: String) extends AnyVal

def m(name: UserName) = name.name.length

m("12345") //> error: type mismatch
m(new UserName("12345")) //> 5

Value classes have a very small footprint, in fact they operate with their underlying object directly. If you look at the generated code it will in fact be:

def m(name: String): Int = name.length();
m("12345")

type shines when you need to create type expressions, e.g.:

type ¬[A] = A => Nothing
type ¬¬[A] = ¬[¬[A]]
type ∨[T, U] = ¬[¬[T] with ¬[U]]
type |∨|[T, U] = { type λ[X] = ¬¬[X] <:< (T ∨ U) }

(the first thing which came my mind, credit to Miles Sabin)

Victor Moroz
  • 9,167
  • 1
  • 19
  • 23
0

when you build your own library, you would like to expose nice DSL to work with your library. sometimes it is done by implicits to create infix operators. you can take a look at : infix operator

when you create implicit for your type it wouldn't happen for String, unless you convert that string to your type.

whats the value ? safety when you use implicits.

Community
  • 1
  • 1
David H
  • 1,346
  • 3
  • 16
  • 29