Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make two function parameters as implicit

Tags:

scala

Assume we have Object that takes function as parameter of apply method:

object Wrapper {
  def apply(block: TypeA => String) = {
    TypeA a = ...
    block(a)
  }
}

TypeA is domain type of application.

Now when I define inline block I can define TypeA parameter as implicit:

Wrapper { implicit a => functionThatUseImplicitA() } 

But what if block parameter is not Function1, but Function2? How can I define both parameters as implicit?

object Wrapper2 {
  def apply(block: (TypeA, TypeB) => String) = {
    TypeA a = ...
    TypeB b = ...
    block(a, b)
  }
}

This one does not work:

Wrapper { implicit (a, b) => functionThatUseImplicitAB() } 

The only workaround is define them as vals:

Wrapper { (a, b) => 
  implicit val ia = a
  implicit val ib = b
  functionThatUseImplicitAB()
} 

Thanks!

like image 555
1esha Avatar asked Jun 25 '13 11:06

1esha


People also ask

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.

What is a implicit parameter?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.

How many implicit parameters can a method have?

A method or constructor can have only one implicit parameter list, and it must be the last parameter list given. A method with implicit parameters can be applied to arguments just like a normal method.

What is implicit by the argument of a function?

An implicit argument of a function is an argument which can be inferred from contextual knowledge. There are different kinds of implicit arguments that can be considered implicit in different ways. There are also various commands to control the setting or the inference of implicit arguments.


1 Answers

According to the SLS 6.23 Anonymous Functions implicit keyword is allowed only for single argument functions:

Expr ::= (Bindings | [‘ implicit ’] id | ‘_’) ‘=>’ Expr
ResultExpr ::= (Bindings | ([‘ implicit ’] id | ‘_’) ‘:’ CompoundType) ‘=>’ Block

So you can't make two function parameters as implicit.

This is the one of reasons to use curried functions:

object Wrapper {
  def apply(block: TypeA => TypeB => String) = ???
}

Wrapper { implicit a => implicit b =>
  functionThatUseImplicitAB()
} 
like image 72
senia Avatar answered Oct 05 '22 05:10

senia