简体   繁体   English

为什么我不能在scala中专门研究泛型函数?

[英]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. 我收到一个错误消息,说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? 有人可以用外行的方式向我解释专业化的规则是什么?

The @specialized annotation can be used both for class and method type parameters. @specialized批注可用于类和方法类型参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM