Can extractors be customized with parameters in the body of a case statement (or anywhere else that an extractor would be used)?

前端 未结 5 1242
情书的邮戳
情书的邮戳 2020-12-06 10:15

Basically, I would like to be able to build a custom extractor without having to store it in a variable prior to using it.

This isn\'t a real example of how I would

5条回答
  •  星月不相逢
    2020-12-06 10:54

    One can customize extractors to certain extent using implicit parameters, like this:

    object SomeExtractorBuilder {
      def unapply(s: String)(implicit arg: Boolean): Option[String] = if (arg) Some(s) else None
    }
    
    implicit val arg: Boolean = true
    "x" match {
      case SomeExtractorBuilder(result) =>
        result
    }
    

    Unfortunately this cannot be used when you want to use different variants in one match, as all case statements are in the same scope. Still, it can be useful sometimes.

提交回复
热议问题