alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (lift-and-unlift.scala)

This example Scala source code file (lift-and-unlift.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

array, array, int, int, none, partialfunction, partialfunction, some, test, unit, unit

The Scala lift-and-unlift.scala source code

import Function.unlift

object Test {
  def evens1(x: Int) = if (x % 2 == 0) Some(x) else None
  def evens2: PartialFunction[Int, Int] = {
    case x if x % 2 == 0  => x
  }
  
  def main(args: Array[String]): Unit = {
    val f1 = evens1 _
    val f2 = evens2.lift
    
    assert(1 to 10 forall (x => f1(x) == f2(x)))
    
    val f3 = unlift(f1)
    val f4 = unlift(f2)
    
    assert(1 to 10 forall { x =>
      if (!f3.isDefinedAt(x)) !f4.isDefinedAt(x)
      else f3(x) == f4(x)
    })
    
    assert(f1 eq f3.lift)
    // Hmm, why is this not true:
    // assert(f2 eq f4.lift)
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala lift-and-unlift.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.