scala.util.Try
import scala.util.Try
import java.net.URL
def parseURL(url: String): Try[URL] =
Try(new URL(url))
scala> parseURL("https://www.salesforce.com").isSuccess
res6: Boolean = true
scala> parseURL("222").isSuccess
res4: Boolean = false
Option
- Represents optional values. Instances of Option are either an instance of scala.Some or the object None.
val greeting: Option[String] = Some("Hello world")
val greeting: Option[String] = None
case class User(
id: Int,
firstName: String,
lastName: String,
age: Int,
gender: Option[String])
object UserRepository {
private val users = Map(1 -> User(1, "John", "Doe", 32, Some("male")),
2 -> User(2, "Johanna", "Doe", 30, None))
def findById(id: Int): Option[User] = users.get(id)
def findAll = users.values
}
Option - contd.
scala> if (user1.isDefined) {
| println(user1.get.firstName)
| }
John
scala> val user = User(2, "Johanna", "Doe", 30, None)
user: User = User(2,Johanna,Doe,30,None)
scala> println("Gender: " + user.gender.getOrElse("not specified"))
Gender: not specified
scala> val user = User(2, "Johanna", "Doe", 30, None)
user: User = User(2,Johanna,Doe,30,None)
scala> val gender = user.gender match {
| case Some(gender) => gender
| case None => "not specified"
| }
gender: String = not specified
scala> println("Gender: " + gender)
Gender: not specified