How to pass an implicit parameter when creating a function object

Asked 1 years ago, Updated 1 years ago, 82 views

How should I pass an implicit parameter when I create a function object?

If you do not specify anything, you will get an error (in the part of val process=):

case class Cache (key:Int, value: String)

US>class Processor {
  val process=processF_//could not find implicit value for parameter cache:this.Cache

  private def processF() (implicit cache:Cache): String=cache.value
}

object Main {
  def run() {
    implicit val cache = Cache (10, "hello")

    val processor = new processor
    processor.process()
  }
}

Main.run

I wish I could write it like this, but it doesn't work.

val process:()(implicit cache:Cache)=>String=processF_// syntax error

I don't know if it's possible in the first place, but could you tell me what kind of approach is effective?Thank you for your cooperation.

scala

2022-09-30 19:32

1 Answers

I don't know if it matches the questioner's intentions, but how about passing the constructor argument to implicit?
(For the sake of simplicity, we set the Main object to App.)

case class Cache (key:Int, value: String)

class Processor (implicit c: Cache) {
  //implicit val cache2 = Cache(20, "hola")
  val process=processF_
  private def processF() (implicit cache:Cache): String=cache.value
}

object Main extensions App {
  implicit val cache = Cache (10, "hello")
  val processor = new processor
  println(processor.process())
}

If implicit precedes val, like cache2, they will go and see it.


2022-09-30 19:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.