Search code examples
scalareflectionshapeless

Does Shapeless use reflection and is it safe to use in scala production code?


I'm still a bit confused about the scala Shapeless library after reading many articles. It seems that Shapeless uses scala compiling features? So does it use reflection and is it safe for production code?


Solution

  • Shapeless doesn't use reflection, it uses macros to inspect the structure of classes. With Shapeless this inspection happens at compilation time and not runtime (reflection happens at runtime). As a result of this Shapeless can be considered safer than reflection because it will be able to make many checks at compilation time.

    Let's try to get a field by name using shapeless

    case class MyClass(field: String)
    import shapeless._
    val myClassLens = lens[MyClass] >> 'field
    val res = myClassLens.get(MyClass("value")) // res == "value"
    

    if we use an invalid field name the compiler will complain with a compilation error

    On the other hand if we tried to achieve this same thing using reflection the field name would be checked at runtime (maybe in production), that's why reflection is not considered as safe as Shapeless. It will also be way faster with Shapeless than reflection