Skip to content
This repository has been archived by the owner on May 29, 2020. It is now read-only.

Commit

Permalink
[split] Add ExceptionalFunction0 for easier use from Java
Browse files Browse the repository at this point in the history
  • Loading branch information
John Corwin committed Feb 7, 2012
1 parent 30b58f5 commit 35ed8e3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions util-core/src/main/scala/com/twitter/util/Function.scala
Expand Up @@ -2,6 +2,16 @@ package com.twitter.util

abstract class Function0[R] extends (() => R)

abstract class ExceptionalFunction0[R] extends Function0[R] {
/**
* Implements apply in terms of abstract applyE, to allow Java code to throw checked exceptions.
*/
final override def apply(): R = applyE()

@throws(classOf[Throwable])
def applyE(): R
}

/**
* This class is for Java friendliness. Any Scala method that takes Function1[A, B]
* can now take a Function[A, B]. Because Function1 is a trait, it is very difficult
Expand Down
17 changes: 17 additions & 0 deletions util-core/src/test/java/com/twitter/util/FunctionTest.java
Expand Up @@ -22,4 +22,21 @@ public String applyE(Integer in) throws Exception {
// pass: expected
}
}

/** Confirm that we can extend ExceptionalFunction0 with applyE(). */
public void testExceptionalFunction0() {
ExceptionalFunction0<Integer> fun = new ExceptionalFunction0<Integer>() {
@Override
public Integer applyE() throws Exception {
throw new Exception("Expected");
}
};
try {
fun.apply();
assert false : "Should have thrown";
} catch (Exception e) {
// pass: expected
}
}

}

0 comments on commit 35ed8e3

Please sign in to comment.