Today I was trying to make a safe navigation operator in Scala. The idea is to use Option instead of reference with possible null value.
implicit class SafeNavigation[A](o: Option[A]) { def ?[B](a: A => Option[B]): Option[B] = if (o.isEmpty) None else a(o.get) } class Test1(s: String) { var f: Option[String] = Some(s) var f2: Option[String] = None val t2: Option[Test2] = Some(new Test2(1)) val t2b: Option[Test2] = None } class Test2(i: Int) { def f: Option[Int] = Some(i) def f2: Option[Int] = None } val x2: Option[Test1] = None x2?(_.f)?(s => Some(s.length)) // None val x3 = Some(new Test1("test")) x3?(_.f)?(s => Some(s.length)) // Some(4) x3?(_.f2)?(s => Some(s.length)) // None x3 ? (_.t2) ? (_.f) ? (i => Some(i+2)) ? (i => if (i > 0) Some(i.toString + " int") else None) // Some(3 int) x3?(_.t2)?(_.f2)?(i => Some(i+2)) // None
No comments:
Post a Comment