Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can implicits with multiple inputs be used in Scala?

Tags:

scala

implicit

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 = ... //?

Thanks

like image 787
Dimitris Andreou Avatar asked Mar 10 '10 12:03

Dimitris Andreou


1 Answers

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.

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

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.

UPDATE

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]
like image 93
retronym Avatar answered Sep 17 '22 19:09

retronym