【问题标题】:Apply Method with Implicits Partially [duplicate]应用部分隐含的方法[重复]
【发布时间】:2015-04-20 17:57:01
【问题描述】:

给定以下方法:

scala> def f(x: Int)(implicit y: Int, z: Int) = x + y + z
f: (x: Int)(implicit y: Int, implicit z: Int)Int

我可以定义一个隐式,然后应用它。

scala> implicit val x: Int = 5
x: Int = 5

scala> f(10)
res0: Int = 20

但是,显然,我不能只指定一个隐式参数:

scala> f(10)(y = 10)
<console>:10: error: not enough arguments for method f: 
    (implicit y: Int, implicit z: Int)Int.
Unspecified value parameter z.
              f(10)(y = 10)
                   ^

是否可以指定隐式参数,即y,但将z 留给隐式解析?

【问题讨论】:

    标签: scala


    【解决方案1】:

    您可以使用implicitly method来满足参数列表的要求:

    scala> f(10)(y = 10, implicitly)
    res0: Int = 25
    

    由于它是Predef 的一部分,因此无需任何导入语句即可使用。

    【讨论】:

    • 不错的收获。但是在命名y = 10 之前传递位置implicitly 会更好,因为f(10)(z = 10, implicitly) 不会编译。
    • @Odomontois :是的,在这一点上,命名参数几乎是多余的 - 但是,我想尽可能接近问题示例的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2014-01-01
    • 2011-12-05
    • 2023-03-29
    • 2011-04-19
    相关资源
    最近更新 更多