【问题标题】:Scala implicit conversion for type aliases类型别名的 Scala 隐式转换
【发布时间】:2017-08-23 13:36:59
【问题描述】:

定义

type TA[T] = T => Int

implicit class TAOps[T](a: TA[T]) {
  def foo(): Unit = {println("TA")}
}

val ta: TA[Double] = x => x.toInt

现在,

ta.foo()

编译失败,提示value foo is not a member of ammonite.$sess.cmd1.TA[Double]

当显式调用时

TAOps(ta).foo()

打印TA。为什么隐式转换在前一种情况下不起作用?

【问题讨论】:

    标签: scala type-alias implicits


    【解决方案1】:

    您的隐式定义期望接收一个类型参数的类型,即TA[T]

    您的声明:val ta: TA[Double] = ... 是它自己的类型,并且不接受任何类型参数。所以编译器不会使用你的隐式 def 来检查这个。

    结论您对带有类型参数的类型进行了隐式类型转换,而TA[Double] 不采用任何类型参数。

    解决方案:

    1 - 替换隐式类型转换以接收Function1:

      implicit class TAOps[T](a: T => Int) {
        def foo: Unit = {
          println("TA")
        }
      }
    

    2 - 使用类型 lambda:

      implicit class TAOps[T](a: ({type Alias = TA[T]})#Alias) {
        def foo: Unit = {
          println("TA")
        }
      }
    

    这里你创建的类型是柯里化的。所以编译器现在会将此隐式转换应用于匹配的类型,它不再期望接收 1 个类型参数的类型。

    更多关于Type Lambdas

    【讨论】:

    • 谢谢你,@pedromss,它有效。我不知道类型参数“孔”在这种情况下发挥作用。
    • 我也发现了困难的方式:P。这能回答你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 2017-08-10
    • 2011-09-12
    • 2011-06-08
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多