具有多个参数的Scala隐式转换 [英] Scala implicit conversions with multiple arguments
问题描述
我一直认为Scala隐式转换只能使用一个参数,如果需要从多个参数进行转换之类的东西,则可以使用元组.但是,我惊讶地发现Scala 2.10.3实际上接受了这个(傻)定义,没有问题:
I've always thought that Scala implicit conversions could only take one argument, and if you needed something like conversion from multiple arguments, you would use a tuple. However, I was surprised to find that Scala 2.10.3 actually accepts this (silly) definition without problem:
scala> implicit def foo(i: Int, j: Int): Int = i
foo: (i: Int, j: Int)Int
是否有任何方式或理由使用这种多参数隐式?
Is there any way or reason to use such a multi-argument implicit?
推荐答案
并非所有隐式
函数都是转换!
Not all implicit
functions are conversions!
任何具有单个参数 的隐式函数都可以用作转换,但这不是唯一的隐式用例.
Any implicit function with a single argument could be used as a conversion, but that's not the only use-case for implicits.
函数只是另一种类型,因此,您可以在(implicit fn:(Int,Int)=> Int)
Functions are just another type and, as such, you can specify an implicit argument as in (implicit fn: (Int, Int) => Int)
但是我不会这样做,您打算以隐式形式传递的任何内容都应具有一个 far 更具体的类型,以便更好地自我记录其预期目的.
I wouldn't do this though, anything you intend to pass as an implicit should have a far more specific type that better self-documents its intended purpose.
这篇关于具有多个参数的Scala隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!