Greg
Greg

Reputation: 11512

Is it possible to pass an implicit to a PartialFunction?

I have a PartialFunction like this:

  val expectNumber: PartialFunction[Int, Int] = {
    case i if isNumberChar(chars(i)) =>
      var j = i
      while (j < max && isNumberChar(chars(j)))
        j += 1
      tokenspace.add(JsonToken(Number, i, j))
      j
  }

I'd like to access an implicit value within this PF, like this perhaps:

  val expectNumber: PartialFunction[Int, Int] = {
    case i if isNumberChar(chars(i)) =>
      val thing = implicitly[String]
      var j = i
      while (j < max && isNumberChar(chars(j)))
        j += 1
      tokenspace.add(JsonToken(Number, i, j))
      j
  }

Or by any other means of passing in an implicit. The code above issues a compile error saying it can't find the implicit. I'm not familiar how (if?) an implicit parameter can be passed into a PartialFunction.

Is what I'm trying to do possible?

Upvotes: 0

Views: 44

Answers (1)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

Yes, you can make expectNumber a def and pass the implicit via it

def expectNumber(implicit ev: String): PartialFunction[Int, Int] = {
    case i if isNumberChar(chars(i)) =>
      val thing = implicitly[String]
      var j = i
      while (j < max && isNumberChar(chars(j)))
        j += 1
      tokenspace.add(JsonToken(Number, i, j))
      j
  }

Upvotes: 2

Related Questions