2016-07-08 8 views
2

スカラでは、クラス型をジェネリック型として渡すか、明示的に渡すのが一般的ですか?スカラ関数の引数:クラスvs関数ジェネリック型。

たとえば、ソース例外、ターゲット例外、および3番目のパラメータを取り込むJavaオブジェクトを作成するためのヘルパー関数を作成しました(この例ではStringを使用します)。私はスタイルだけの問題だと思う

exceptionTranslation(classOf[FooException], classOf[BarException], "blah") 

def exceptionTranslation(sourceClazz: Class[_ <: Throwable], targetClazz: Class[_ <: Throwable], message: String) = new Translation() 
    .withSource(sourceClazz) 
    .withTarget(targetClazz) 
    .withMessage(message) 

それとも

exceptionTranslation[FooException, BarException]("blah") 

def exceptionTranslation[Source <: Throwable, Target <: Throwable](message: String)(
implicit source: ClassTag[Source], target: ClassTag[Target]) = new Translation() 
    .withSource(source.runtimeClass.asInstanceOf[Class[Source]]) 
    .withTarget(target.runtimeClass.asInstanceOf[Class[Target]]) 
    .withMessage(message) 
+1

は、私はあなたがどんな暗黙とランタイムキャストは必要ありませんが、それはだとして最初のものは、より良い好き好みの問題。 –

+0

@Tuvalで同意すると、2番目のものは絶対に過剰です – Chirlo

答えて

1

:Scalaではより良い練習どちらです。彼らはすべて正しいです。個人的には、私はより直感的で、短く、最も力のないものに行きます。

クラスのテキスト名抽出の例:使用

import scala.reflect._ 
def bar[F](x: Class[F]) = x.getName 

def foo[X:ClassTag] = implicitly[ClassTag[X]].runtimeClass.getName 

def foobar[X](implicit ctag: ClassTag[X]) = ctag.runtimeClass.getName 

を:

> bar(classOf[Double]) // This one has better Java interop 
res: String = "double" 

> foo[Double] // This looks slightly less verbose when calling 
res: String = "double" 

> foobar[Double] 
res: String = "double" 
+0

関数はプライベートで、私にとっては関数の汎用型を使用してパラメータが渡されていましたが、関数を呼び出すときには、 「foobar」)。ほとんどの人は例外翻訳のリストを読んでいて、プライベートヘルパー関数を実際には見ていないので、関数の呼び出しを単純化することがより重要であると考えました。 –

関連する問題