1
私の要件は、ジェネリックタイプのタイプパラメータに応じて特性を混合することです。 これに対して、汎用メソッドを取得するには、applyメソッドの暗黙のパラメータとしてTypeTagをに渡しています。アプリケーション固有のmixin特性タイプパラメータに応じたオプション
これは、マップ・メソッドでは、次のコンパイル時にエラーが発生:
not enough arguments for method apply:
(implicit tag: reflect.runtime.universe.TypeTag[B])customOption.AppOption[B] in object AppOption.
Unspecified value parameter tag.
No TypeTag available for B
私はこのアプローチで間違ってやっているものを、提案しており、このアプローチは、私の要件に適合していない場合してください。新しい提案が大歓迎され、歓迎されます。
簡体コード:
package customOption.withGenericMixins
import scala.reflect.runtime.universe._
sealed abstract class AppOption[+A] {
def value: A
def isEmpty: Boolean
def map[B](f: A => B): AppOption[B] = {
if (!isEmpty) {
println("map called : " + value)
}
//compile time error
//not enough arguments for method apply: (implicit tag: reflect.runtime.universe.TypeTag[B])customOption.AppOption[B] in object AppOption.
//Unspecified value parameter tag.
//No TypeTag available for B
if (!isEmpty) AppOption(f(this.value)) else AppOptionNone
}
def flatMap[B](f: A => AppOption[B]): AppOption[B] = {
if (!isEmpty) {
println("flatMap called : " + value)
}
if (!isEmpty) f(this.value) else AppOptionNone
}
}
object AppOption {
def apply[A](value: A)(implicit tag: TypeTag[A]): AppOption[A] = {
if (value == null) {
AppOptionNone
} else {
//Depending on the type, my requirement is to mixin Traits
val genType = tag.tpe.toString
genType match {
case "String" => new AppOptionSome(value) //with XTrait
case "Boolean" => new AppOptionSome(value) //with YTrait
case "Double" => new AppOptionSome(value) //with ZTrait
case _ => throw new RuntimeException(s"$genType not supported by AppOption")
}
}
}
}
case class AppOptionSome[+A](value: A) extends AppOption[A] {
def isEmpty = false
}
case object AppOptionNone extends AppOption[Nothing] {
def value = throw new NoSuchElementException("AppOptionNone.value")
def isEmpty = true
}
TypeTagを型パラメータBに渡す方法 – mogli
同様にしました。 'map [B:TypeTag]'。 –