How can one provide manually specialized implementations with Scala specialization?

后端 未结 3 781
渐次进展
渐次进展 2020-12-28 14:40

Specialization promises to provide high-efficiency implmentations for primitive types with minimal extra boilerplate. But specialization seems to be too eager for its own g

3条回答
  •  隐瞒了意图╮
    2020-12-28 15:24

    This is an answer from the scala internals mailing list:

    With miniboxing specialization, you can use the reflection feature:

    import MbReflection._
    import MbReflection.SimpleType._
    import MbReflection.SimpleConv._
    
    object Test {
      def bippy[@miniboxed A, @miniboxed B](a: A, b: B): B =
        (reifiedType[A], reifiedType[B]) match {
          case (`int`, `int`) => (a.as[Int] + b.as[Int]).as[B]
          case (  _  , `int`) => (b.as[Int] + 1).as[B]
          case (`int`,   _  ) =>  b
          case (  _  ,   _  ) =>  b
        }
    
      def main(args: Array[String]): Unit = {
        def x = 1.0
        assert(bippy(3,4) == 7)
        assert(bippy(x,4) == 5)
        assert(bippy(3,x) == x)
        assert(bippy(x,x) == x)
      }
    }
    

    This way, you can choose the exact behavior of the bippy method based on the type arguments without defining any implicit classes.

提交回复
热议问题