0
votes

I am playing around with Scala at the moment and the pattern matching. I have the general idea behind it and can get the basics working. My issue is with Option[]. It is possible to use pattern matching on Option[]'s?

What I am trying to do is make a little function that will take in an option[String] parameter and then based on the input return the string if its a string and a heads up if not. I amnt too sure on how to go about this though, I have tried a few thing but it either gives out or in the case below will never hit the second case.

def getString(someString: Option[String]): String =
        someString match {
          case s: Option[String] => someString //also tried things like case: String => ...
          case _ => s"no string entered" //and things like case _ => ...
        }
1
Try case Some(someString) => someString - The fourth bird
It seems you do not understand pattern matching since you are not checking for any pattern. Also, it seems you do not know how the option type works. I would suggest you to follow any basic tutorial or introductory book since this is basic behavior of the language. - Luis Miguel Mejía Suárez
Fantastic, thank you very much! Must have tried everything but that. Just for clarification this is going to match then in the event that there is some value in some string being passed in? Why is it not possible to use case s:String then as it is still passing in a string? - RJHaze
@LuisMiguelMejíaSuárez, just starting out and getting confused is all. I am following through the Essential Scala book at the moment - RJHaze
@RoryHayes Option[T] is an ADT it is either Some(value: T) or None. So when you pattern match you may check for those two possibilities. - Also case x: C what that does is checking if x is an instance of the class C, so if you already know that s is an Option then it doesn't make sense to test if it is an instance of String. - Luis Miguel Mejía Suárez

1 Answers

2
votes

This is the easiest way to implement your function:

def getString(someString: Option[String]): String =
  someString.getOrElse("no string entered")

If you want to use match it looks like this:

def getString(someString: Option[String]): String =
  someString match {
    case Some(s) => s
    case _ => "no string entered"
  }