How to annotate a parameter as implicit in pattern matching when retrieving values

I have a class like

case class A(a: Int, b: String) 

and functions

 def f(a: Int)(implicit b: String) =??? 

Is it possible to do something like this?

 val a = A(11, "hello") a match { case A(a, implicit b) => f(a) } 

How can I make parameter b implicit without explicitly declaring it after retrieval.

+5
source share
1 answer

I would not worry about passing the argument implicitly, as you can easily specify it explicitly in this particular case:

 case class A(a: Int, b: String) def f(a: Int)(implicit b: String) =??? val a = A(11, "hello") a match { case A(a, b) => f(a)(b) } 

If you must pass a value implicitly, it must be declared in the scope. For instance:

 a match { case A(a, b) => { implicit val s = b f(a) } } 

Also, as already stated, do not use implicit with a generic type. This is better if you wrap it in another class:

 case class A(a: Int, b: String) case class SomeCustomString(s: String) def f(a: Int)(implicit b: SomeCustomString) =??? val a = A(11, "hello") a match { case A(a, b) => { implicit val s = SomeCustomString(b) f(a) } } 

If you could explain the use case for an implicit argument, I could provide a better example.

Update . There is a way to do what you need:

 case class SomeCustomString(s: String) case class A(a: Int, b: String) { implicit val s = SomeCustomString(b) } def f(a: Int)(implicit s: SomeCustomString) =??? val a = A(11, "hello") import a._ f(aa) 

Or, if you must have it according to the pattern, this last bit will look like this:

 a match { case x: A => { import x._ f(xa) } } 

Update 2 : or another approach (again, with implicit pretty much redundant):

 case class SomeCustomString(s: String) case class A(a: Int, b: String) { implicit val s = SomeCustomString(b) def invokeF = f(a) } def f(a: Int)(implicit s: SomeCustomString) =??? val a = A(11, "hello") a.invokeF 

or

 a match { case x: A => x.invokeF } 

Does it help?

+3
source

Source: https://habr.com/ru/post/1275877/


All Articles