extractor

Replacing case class inheritance with extractors preserving exhaustiveness checks in Scala

强颜欢笑 提交于 2019-11-30 03:15:04
问题 I have a simple class hierarchy that represents a graph-like structure with several distinct types of vertexes implemented using case classes: sealed trait Node sealed abstract case class Vertex extends Node case class Arc extends Node case class VertexType1 (val a:Int) extends Vertex case class VertexType2 (val b:Int) extends Vertex This allows me to write match blocks like this: def test (x: Node) = x match { case _ : Arc => "got arc" case _ : Vertex => "got vertex" } or like this: def test

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

时光毁灭记忆、已成空白 提交于 2019-11-27 23:37:06
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 use it, it would more likely be used in the case of a regular expression or some other string pattern like construct, but hopefully it explains what I'm looking for: def someExtractorBuilder(arg:Boolean) = new { def unapply(s:String):Option[String] = if(arg) Some(s) else None } //I would like to be able to use something like this val {someExtractorBuilder(true)}(result) = "test" "test" match {case {someExtractorBuilder(true)}(result