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

Scala example source code file (pf-catch.scala)

This example Scala source code file (pf-catch.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

anyref, anyref, array, debug, handler, handler, partialfunction, t, t, test, test, unit

The Scala pf-catch.scala source code

object Test {
  def shortName(x: AnyRef) = x.getClass.getName split '.' last
  type Handler[+T] = PartialFunction[Throwable, T]

  val standardHandler: Handler[String] = {
    case x: java.util.NoSuchElementException    => shortName(x)
    case x: java.lang.IllegalArgumentException  => shortName(x)
  }
  
  def fn[T: Handler](body: => T): T = {
    try body
    catch implicitly[Handler[T]]
  }
  
  def f1 = {
    implicit val myHandler = standardHandler
    println(fn(Nil.head))
    println(fn(null.toString))
  }
  def f2 = {
    implicit val myHandler: Handler[String] = standardHandler orElse {
      case x => "DEBUG: " + shortName(x)
    }
    println(fn(Nil.head))
    println(fn(null.toString))
  }

  def main(args: Array[String]): Unit = {
    try f1
    catch { case x => println(shortName(x) + " slipped by.") }
    
    f2
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala pf-catch.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.