stian
stian

Reputation: 1987

How to use pattern matching in this if/else?

I wrote an function with an if/else-clause, but thought about possibilities to use pattern matching. I failed, but would appreciate seeing how it could have been done for the learning outcome of it.

def sha1():String = {
    if (System.getProperty("os.name").contains("OS X")){
       ("x.tif" !!).toString
    }
    else{
      "failed"
    }
}

I tried this with the logic that i hoped that the string would take part in the test ("test" contains("0S X") is legal). This causes an error.

 def sha2(command:String):String = System.getProperty("os.name") match {
    case contains("OS X")=> ("x.tif" !!).toString

} 

The second attempt would be to write something like, where I match on the input to a function call:

def sha3():String = System.getProperty("os.name").contains(x) match {
    case x=="OS X" => "hello"
}

Upvotes: 0

Views: 168

Answers (2)

Dima
Dima

Reputation: 40500

You don't need pattern matching for this. Just do:

"OS X".r
  .findFirstIn(System.getProperty("os.name"))
  .map { _ => ("x.tif" !!).toString }
  .getOrElse("failed")

Upvotes: 0

Andreas Neumann
Andreas Neumann

Reputation: 10884

This would be an option to express by using pattern match

def sha1():String = System.getProperty("os.name") match {
  case s if s.contains("OS X") => ("x.tif" !!).toString
  case _ => "failed"
}

If your code really has just one case then approach using if elsecould be nicer though

def sha1(): String = 
  if ( System.getProperty("os.name").contains("OS X") )
    ("x.tif" !!).toString
  else
    "failed"

Upvotes: 3

Related Questions