【问题标题】:Could not find implicit value for parameter in scala在 scala 中找不到参数的隐式值
【发布时间】:2018-09-12 16:35:51
【问题描述】:
    def p1(c: Int)(implicit b: Int): Unit = {
        println(c + b)
    }

    def p2(a: Int, b: Int): Unit ={
        p1(a)
    }

    p2(5, 6) //result = 11

错误:找不到参数 b 的隐式值:Int

如何解决问题但不要使用此解决方案

 def p2(a: Int, b: Int): Unit ={
        implicit val bb = b
        p1(a)
    }

【问题讨论】:

    标签: scala implicit


    【解决方案1】:

    一种方法是显式传递b

    def p2(a: Int, b: Int): Unit ={
        p1(a)(b)
    }
    

    第二种方法是将b标记为隐含在p2的签名中

    def p2(a: Int)(implicit b: Int): Unit ={
      p1(a)
    }
    

    【讨论】:

    • 感谢您的回答,但我想只使用带有参数“a”的 p1:p1(a)。您的第二个答案在编译时失败。
    • @TrầnTúNam 没有办法做到这一点。除了implicit 在范围内。
    猜你喜欢
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2017-02-02
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多