Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Created September 29, 2012 17:07
Show Gist options
  • Save dcbriccetti/3804602 to your computer and use it in GitHub Desktop.
Save dcbriccetti/3804602 to your computer and use it in GitHub Desktop.
How would you avoid the Option.get?
case class Dog(name: String, tailLength: Option[Int])
val dogs = Seq(Dog("Sparky", Some(85)), Dog("Rotty", None))
val (dogsWithTails, dogsWithoutTails) = dogs.partition(_.tailLength.isDefined)
if (! dogsWithoutTails.isEmpty)
println("These dogs are missing tails: " +
dogsWithoutTails.map(_.name).mkString(", "))
dogsWithTails.map(dog => {
val tailLength = dog.tailLength.get // We know it exists because of the partition above
// ⋮
})
// More realistic version:
case class Dog(name: String, tailLength: Option[Int], weight: Int)
val dogs = Seq(Dog("Sparky", Some(85), 10), Dog("Rotty", None, 15))
val (dogsWithTails, dogsWithoutTails) = dogs.partition(_.tailLength.isDefined)
if (! dogsWithoutTails.isEmpty)
println("These dogs are missing tails: " +
dogsWithoutTails.map(_.name).mkString(", "))
dogsWithTails.map(dog => {
val tailLength = dog.tailLength.get // We know it exists because of the partition above
someWorkWithSideEffects(tailLength, dog.weight)
})
def someWorkWithSideEffects(tailLength: Int, weight: Int) {
// ⋮
}
@harryh
Copy link

harryh commented Sep 29, 2012

Even though we know that all dogsWithTails have a tailLength I still might do:

dogsWithTails.map(dog => {
  dog.tailLength.map(tailLength => {
    someWorkWithSideEffects(tailLength, dog.weight)
  })
})

@harryh
Copy link

harryh commented Sep 29, 2012

Even though we know that all dogsWithTails have a tailLength I still might do:

dogsWithTails.map(dog => {
  dog.tailLength.map(tailLength => {
    someWorkWithSideEffects(tailLength, dog.weight)
  })
})

@harryh
Copy link

harryh commented Sep 29, 2012

Even though we know that all dogsWithTails have a tailLength I still might do:

dogsWithTails.map(dog => {
  dog.tailLength.map(tailLength => {
    someWorkWithSideEffects(tailLength, dog.weight)
  })
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment