2013-08-20 12 views
5

私はScalaでJava Exceptionを拡張する最も単純ではあるが適切な方法を探しています。 new Exception(null, cause)new Exception(cause)Throwable.javaに応じて異なる動作を持っているので、たとえば、次が正しくありません:ScalaでJava例外を正しく拡張するにはどうすればよいでしょうか?

class InvalidVersionException(message: String = null, cause: Throwable = null) 
    extends IllegalArgumentException(message, cause) { 
    def this(message: String) = this(message, null) 
    // This is not same with super(cause) 
    def this(cause: Throwable) = this(null, cause) 
} 

私はcause.toString()Throwable(cause)セットメッセージを知っているので、私は、次のを思い付いた:

class InvalidVersionException(message: String = null, cause: Throwable = null) 
    extends IllegalArgumentException(if ((message eq null) && (cause ne null)) cause.toString else message, cause) { 
    def this(message: String) = this(message, null) 
    def this(cause: Throwable) = this(null, cause) 
} 

しかし、これはまだあります:

if ((message eq null) && (cause ne null)) cause.toString 

から複製されています。

コードを重複せずにExceptionを拡張するより良い方法はありますか?

答えて

0

、私は次のようになってしまった:

class InvalidVersionException(message: String, cause: Throwable = null) 
    extends IllegalArgumentException(message, cause) { 
    def this(cause: Throwable) = this(if (cause ne null) cause.toString else null, cause) 
    def this() = this(null) 
} 

.. 54のバイトを保存します。

2

あなただけの原因のみのコンストラクタに変更することができるはずのようにそれは私になります「(ないメッセージ)を交換していない

def this(cause: Throwable) = this(if (cause == null) "(no message)" else cause.toString, cause) 

def this(cause: Throwable) = this(cause.toString, cause) 

EDIT:nullの原因を処理するには"はnull(推奨されません)またはあなたが感じるテキストが適切です。

+0

'cause'が' null'の場合、 'NullPointerException'を送出します。 – trustin

+0

@trustinフェアポイント。私の答えをそれを扱う一つの方法で編集しました。 – Shadowlands

0

これはいかがですか? @Shadowlandsによって回答に基づいて

( " In Scala, how can I subclass a Java class with multiple constructors?" 経由)
trait InvalidVersionException extends IllegalArgumentException 

object InvalidVersionException { 
    def apply(msg: String) = new IllegalArgumentException(msg) with InvalidVersionException 
    def apply(cause: Throwable) = new IllegalArgumentException(cause) with InvalidVersionException 
    def apply(msg: String, cause: Throwable) = new IllegalArgumentException(msg, cause) with InvalidVersionException 
} 

+0

例外を特質にするのが良いかどうかは分かりません。それは本当に任意のクラスがそれを拡張できることを意味しないのですか? – trustin

関連する問題