如何在Scala中使用具有多个输入的隐式? [英] How can implicits with multiple inputs be used in Scala?

查看:55
本文介绍了如何在Scala中使用具有多个输入的隐式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何编写一个隐式应用以下内容的表达式:

For example, how can I write an expression where the following is implicitly applied:

implicit def intsToString(x: Int, y: Int) = "test"

val s: String = ... //?

谢谢

推荐答案

一个参数的隐式函数用于将值自动转换为期望的类型.这些被称为隐式视图.有两个参数,这是行不通的或没有道理的.

Implicit functions of one argument are used to automatically convert values to an expected type. These are known as Implicit Views. With two arguments, it doesn't work or make sense.

您可以将隐式视图应用于TupleN:

You could apply an implicit view to a TupleN:

implicit def intsToString( xy: (Int, Int)) = "test"
val s: String = (1, 2)

您还可以将任何函数的最终参数列表标记为隐式.

You can also mark the final parameter list of any function as implicit.

def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = intsToString

或者,结合使用implicit的这两种用法:

Or, combining these two usages of implicit:

implicit def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = implicitly[String]

但是在这种情况下,它并不是真正有用的.

However it's not really useful in this case.

更新

要详细说明马丁的评论,这是有可能的.

To elaborate on Martin's comment, this is possible.

implicit def foo(a: Int, b: Int) = 0
// ETA expansion results in:
// implicit val fooFunction: (Int, Int) => Int = (a, b) => foo(a, b)

implicitly[(Int, Int) => Int]

这篇关于如何在Scala中使用具有多个输入的隐式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆