【问题标题】:Extend user defined higher kinded type扩展用户定义的高级类型
【发布时间】:2013-03-04 09:49:54
【问题描述】:

我在 scala 中有一个用户定义的更高种类的别名:

type FutureOfLastError = Future[LastError]

我也有这种类型的值:

val myFuture: FutureOfLastError = ...

为了编写可读的代码,我想定义(例如)一个类似的方法

def mapToString = { ... }

将 FutureOfLastError 的实例映射到 Future[String] 并像这样调用它

myFuture mapToString

我该怎么做?甚至可能吗?我已经尝试过封装在一个案例类中,我想到了各种隐式转换。

我最喜欢的选择是类型别名上的伴随对象,但我无法让它工作,因为我无法从伴随对象调用特征 Future 的方法(如 map 等)。

【问题讨论】:

    标签: scala implicit-conversion higher-kinded-types companion-object


    【解决方案1】:

    您不需要实际扩展类,只需使用隐式类(这只是“丰富我的库”模式的语法糖)。 像这样简单的事情应该可以做到:

    implicit class MyFutureOps( future: FutureOfLastError ) {
      def mapToString = future.map(_.toString)
    }
    

    【讨论】:

    • 太棒了。非常感谢您很快的答复。它工作完美。到目前为止,我只是不知道隐式类(我只是一个 scala 初学者,你可能已经猜到了...... ;-))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2011-04-20
    相关资源
    最近更新 更多