1

类型宏已关闭。

但是,我有两个需要它们的重要用例。结果是我的应用程序的可扩展性严重丧失。两者都是给定其他类型的类型的动态编译时生成。基本上我想做类似的事情(显然不是scala代码,但我想你会明白的):

type T[U] = macro usecase1[U]

def usecase1[U]= U match {  
  case t if (t <:< Int) => String
  case ... => ...
}

第二个用例是:

type Remaining[A, B >: A] = macro ...

例如在哪里

class C
trait T1 extends C
trait T2 extends C

type Remaining[C with T1 with T2, T2] is assigned to "C with T1" at compile time
(so the macro would have generated the subclass list, and generated a new type from the list without T2) 

我没有用宏来做,所以这是假设。我计划现在就这样做..直到我看到那个类型的宏已经死了。无论如何,有没有人知道获得这些功能的诀窍?谢谢

4

1 回答 1

1

据我所知,第一个用例在某种程度上确实可以通过隐式实现。这是一个可能看起来如何的示例:

scala> trait Bound[A] {
     |   type Type
     | }
defined trait Bound

scala> implicit val bound1 = new Bound[Int] { type Type = String }
bound1: Bound[Int]{type Type = String}

scala> implicit val bound2 = new Bound[String] { type Type = Double }
bound2: Bound[String]{type Type = Double}

scala> val tpe = implicitly[Bound[Int]]
tpe: Bound[Int] = $anon$1@2a6b3a99

scala> type U = tpe.Type
defined type alias U

但是之后:

scala> implicitly[U =:= String]
<console>:19: error: Cannot prove that U =:= String.
              implicitly[U =:= String]
                        ^

另一方面:

scala> implicitly[bound1.Type =:= String]
res0: =:=[bound1.Type,String] = <function1>

隐式解析似乎正在丢失一些类型。不知道为什么,以及如何解决这个问题。


对于第二个用例,HLists 立即浮现在脑海中。就像是:

scala> trait Remaining[A <: HList, B] { type Result = Remove[A, B] }
defined trait Remaining

scala> new Remaining[C :: T1 :: T2 :: HNil, T2] {}
res5: Remaining[shapeless.::[C,shapeless.::[T1,shapeless.::[T2,shapeless.HNil]]],T2] = $anon$1@3072e54b

虽然不确定如何将结果组合HList成复合类型。类似(伪代码):

trait Remaining[A <: HList, B] {
  def produceType(
    implicit ev0 : Remove.Aux[A, B, C],
             ev1 : IsCons.Aux[C, H, T],
             ev2 : LeftFolder[T, H, (T1, T2) => T1 with T2]) = ev2
             //                     ^ Not real syntax, type-level function to combine/mix types
  val tpe = produceType
  type Result = tpe.Out
}
于 2013-12-23T10:00:59.607 回答