Search code examples
scalatemplate-specializationspecialized-annotation

Why can't I specialize a generic function in scala?


I get an error saying type N is unused or used in non-specializable positions., for the method with the following signature:

protected def offsetFrom0[@specialized(Int,Long) N](offsetFrom1 : Codec[N])(implicit N : Integral[N]) : Codec[N]

Can someone explain to me in layman's terms what the rules are around specialization?


Solution

  • The @specialized annotation can be used both for class and method type parameters.

    def gethead[@specialized(Int,Float,Double) T: Numeric](items: T*): T = items(0)
    gethead(4,57,32) // Result: 4
    

    So in your case you can do something along the lines of:

    case class Offset[@specialized(Int, Long) N](offsetFrom1: N) {
        def offsetFrom0: N = ???
    }
    
    Offset(1).offsetFrom0
    Offset(1L).offsetFrom0