Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Passing one implicit parameter implicitly and the other explicitly. Is it possible?

Tags:

scala

implicit

Let's consider the function:

def foo(implicit a:Int, b:String) = println(a,b).

Now, let us assume that there is an implicit String and Int (implicit val i1=1) in scope but we want to pass an other, not implicit Int (val i2=2) explicitly to foo .

How can we do that ? Is it possible? Thanks for reading.

like image 480
jhegedus Avatar asked Mar 21 '14 07:03

jhegedus


People also ask

How does Scala pass implicit value?

In simpler terms, if no value or parameter is passed to a method or function, then the compiler will look for implicit value and pass it further as the parameter. For example, changing an integer variable to a string variable can be done by a Scala compiler rather than calling it explicitly.

How do you pass an implicit parameter?

The implicit parameter in Java is the object that the method belongs to. It's passed by specifying the reference or variable of the object before the name of the method. An implicit parameter is opposite to an explicit parameter, which is passed when specifying the parameter in the parenthesis of a method call.

How does Scala implicit work?

A method can have an implicit parameter list, marked by the implicit keyword at the start of the parameter list. If the parameters in that parameter list are not passed as usual, Scala will look if it can get an implicit value of the correct type, and if it can, pass it automatically.

Is an implicit parameter to all member functions?

The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.


1 Answers

All I can add is:

def foo(implicit a: Int, b: String) = println(a, b) implicit val i1 = 1 implicit val s = "" val i2 = 2 foo(i2, implicitly[String]) 
like image 179
Peter Schmitz Avatar answered Sep 29 '22 07:09

Peter Schmitz