admin管理员组

文章数量:1332360

Here is a simple example:


    trait RRBound {

      type RR[T]

      def apply[T]: T => RR[T]
    }

    trait Z2 extends RRBound {

      type RR[T] = T match {
        case Option[i] => Seq[i]
      }

      override def apply[T]: T => RR[T] = T match {
        case Option[i] => (v: Option[i]) => v.toSeq
// invalid syntax here
      }
    }

    trait AlsoZ2 {

      def apply[i]: Option[i] => Seq[i] = {v => v.toSeq}
    }

apparently T match can only be used in type definition, so the only way to implement apply[T]: T => RR[T] is by doing it in multiple subtypes, this also means Z2 cannot be converted to AlsoZ2 easily despite that they are functionally identical.

What can be done here to complete Z2 and make AlsoZ2 unnecessary?

Here is a simple example:


    trait RRBound {

      type RR[T]

      def apply[T]: T => RR[T]
    }

    trait Z2 extends RRBound {

      type RR[T] = T match {
        case Option[i] => Seq[i]
      }

      override def apply[T]: T => RR[T] = T match {
        case Option[i] => (v: Option[i]) => v.toSeq
// invalid syntax here
      }
    }

    trait AlsoZ2 {

      def apply[i]: Option[i] => Seq[i] = {v => v.toSeq}
    }

apparently T match can only be used in type definition, so the only way to implement apply[T]: T => RR[T] is by doing it in multiple subtypes, this also means Z2 cannot be converted to AlsoZ2 easily despite that they are functionally identical.

What can be done here to complete Z2 and make AlsoZ2 unnecessary?

Share Improve this question asked Nov 21, 2024 at 3:03 tribbloidtribbloid 3,86815 gold badges71 silver badges120 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Can you make apply inline?

trait RRBound {
  type RR[T]
  inline def apply[T]: T => RR[T]
}

Try

import scalapiletime.{erasedValue, summonFrom}

override inline def apply[T]: T => RR[T] = (v: T) => summonFrom {
  case given (T =:= Option[i]) => summonFrom {
    case given (Seq[`i`] =:= RR[T]) => (v: Option[`i`]).toSeq
  }
}

or

override inline def apply[T]: T => RR[T] = (v: T) => erasedValue[T] match {
  case _: Option[i] => summonFrom {
    case given (T =:= Option[`i`]) => (v: Option[`i`]).toSeq
  }
}

本文标签: In Scala 3how to write a term of which type signature is a match typeStack Overflow