0

Im looking to create a pattern matcher which doesnt require value extraction, and havent found a very satisfying way of doing this. Suppose I have the following illustrative example:

I want to match on Any being an Int

a:Any match {
  case IsAnInt => println(s"$a is an int")
}

Now the closest I can get is either boolean

a:Any match {
  case IsAnInt(true) => println(s"$a is an int")
}

object IsAnInt { 
  def unapply(a:Any):Option[Boolean] = Some(a.isInstanceOf[Int]) 
}

or unit

a:Any match {
  case IsAnInt(()) => println(s"$a is an int")
}

object IsAnInt { 
  def unapply(a:Any):Option[Unit] = if (a.isInstanceOf[Int]) Some(()) else None
}

Which I can do, but isnt nearly as cool... Is there any trick Im not aware of to achieve the first case?

(just to clarify the example is a simplification, I'm not looking for ways to identify an int)

2 Answers 2

3

Try pattern matching on the type like this,

(1: Any) match {
  case v: Int => println(s"$v is an int")
  case ______ => println("not an int")
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use a boolean extractor, i.e. an extractor that just returns a boolean (instead of an Option) to indicate whether it matches:

object IsAnInt {
  def unapply(a : Any) : Boolean = a.isInstanceOf[Int]
}

val x : Any = 3
x  match {
  case IsAnInt() => println("Is an int")
  case _ => println("Is not an int")
}

You still have the parenthesis to seperate matching the object from the extractor though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.