【问题标题】:implict conversion to StringOps not applied within a implict val function body隐式 val 函数体内未应用到 StringOps 的隐式转换
【发布时间】:2013-10-21 23:43:30
【问题描述】:

在以下代码 sn-p 中(使用 scala 2.10.3)TestClass1 编译时出现错误“value toInt is not a member of String”但 >TestClass2 编译良好:

trait TestTrait {
  implicit def test: (String => Int)
}

object TestClass1 extends TestTrait {
  implicit val test = (value: String) => value.toInt
}

object TestClass2 extends TestTrait {
  implicit def test = (value: String) => value.toInt
}

通过augmentString()提供toInt函数的StringOps隐式转换在TestClass1中没有应用> 但在 TestClass2 中应用得很好。有人可以告诉我为什么会这样以及如何保持 testval 而不是 def

【问题讨论】:

  • val 在您的 TestClass1 对象的生命周期内只评估一次,因此它不能有任意参数。如果 value 是您的 TestClass1 对象的成员,您可以让它工作:object TestClass1 (value:String) { implicit val test => value.toInt } 但这可能不是您的想法?
  • 这只适用于类而不是对象,对吧?我绝对对使用对象很感兴趣。
  • 据我所知,它也适用于对象。

标签: scala implicit-conversion


【解决方案1】:

我认为,当需要推断返回类型时,这是隐式定义的限制。您与定义递归方法的情况有些相似。也就是说,“开放”的隐式定义在其主体中触发隐式查找,理论上可以是递归的。 (至少这是我对这个限制的解释)。

您可以对类型进行注释:

object TestClass1 extends TestTrait {
  implicit val test: String => Int = value => value.toInt  // or _.toInt
}

或者去掉implicit关键字——因为它是实现TestTrait的隐式方法,你不需要重新声明implicit关键字:

object TestClass1 extends TestTrait {
  val test = (value: String) => value.toInt
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2017-03-11
    • 2019-06-18
    • 2016-08-18
    • 2018-09-25
    相关资源
    最近更新 更多