Is there a way I could replace the myOptionGet
function by an build-in Scala function,
but without making the code more verbose...? :) and with keeping the function chaining with pipe
.
Replacing by Option.get
doesn't work as I found out.
package playground
import scala.util.chaining.scalaUtilChainingOps
object TEST123 {
def main(args: Array[String]): Unit = {
def myOptionGet[T](x: Option[T]): T = x.get
Some("abc") pipe
myOptionGet pipe
println
// prints: abc
}
}
CodePudding user response:
Yes, the code can be made less verbose by using a lambda:
Some("abc") pipe
((o: Option[String]) => o.get) pipe
println
or even shorter with a placeholder:
Some("abc") pipe
(_.get) pipe
println
However, as @cchantep pointed out in a comment, you should never use .get
because it's unsafe. You should either keep the Option
type to denote that the value might not exist (this is the safe variant of Java's null pointer technique), or alternatively, if you have a sensible default value, use myOption.getOrElse("N/A")
.