1

I would like to check if an object is an option.

For example:

val foo: Option[String] = Some("foo")
val bar: String = "bar"

I would like a function kind of isOption:

def isOption(value: Any): Boolean = {
     ???
}

And the result will be:

isOption(foo) // true
isOption(bar) // false
Thomas
  • 1,164
  • 13
  • 41
  • Please refer to documentation first: https://www.scala-lang.org/api/current/scala/Option.html or https://www.tutorialspoint.com/scala/scala_options.htm – Pavel Oct 15 '18 at 12:08

2 Answers2

8

You can write your function as

def isOption(value: Any): Boolean = {
  value match {
    case x : Option[_] => true
    case _ => false
  }
}

On invoking the function

val foo: Option[String] = Some("foo")
val bar: String = "bar"

you will get an output as

res0: Boolean = true
res1: Boolean = false
Chaitanya
  • 3,590
  • 14
  • 33
5

A short solution would be

value.isInstanceOf[Option[_]]

This also wouldn't obfuscate the fact that you have essentially untyped Any-values and instanceof's flying around in your code, which should be avoided, if possible.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93