【问题标题】:Generic Higher kinded types通用高级类型
【发布时间】:2019-03-04 16:02:34
【问题描述】:
class Toto[F[_]]()
val totos: Seq[Toto[_]] = Seq(new Toto[Future[_]], new Toto[IO[_]])
<console>:12: error: _$1 takes no type parameters, expected: one
       val totos: Seq[Toto[_]] = ???
                           ^

我们如何将通配符用于更高种类的类型?
我只想要SeqToto,不管F 是什么。

【问题讨论】:

    标签: scala types existential-type higher-kinded-types


    【解决方案1】:

    如果您可以将Toto 更改为协变,则以下方法可能有效:

    import language.higherKinds
    
    class Toto[+F[_]]()
    
    class Foo[X]
    class Bar[X]
    
    val toto: Toto[F] forSome { type F[X] } = new Toto[Foo]
    val totos = Seq[Toto[F] forSome { type F[X] }](new Toto[Foo], new Toto[Bar])
    

    感觉类似于this one

    如果这种情况在您的代码中更频繁地发生,您也可以考虑通过将 F 转换为 Toto 的类型成员来将其移开:

    import language.higherKinds
    
    class Toto {
      type F[X]
    }
    
    object Toto {
      def empty[A[X]]: Toto = new Toto {
        type F[X] = A[X]
      }
    }
    
    class Foo[X]
    class Bar[X]
    
    val totos: Seq[Toto] = Seq(Toto.empty[Foo], Toto.empty[Bar])
    

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2013-09-15
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多