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.
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.
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.
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.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With