15

パラメーター化された型に固有のパターン マッチをサポートするために、エクストラクターのメソッドでジェネリックをunapply暗黙的な「コンバーター」と共に使用することはできませんか?

私はこれをしたいです(行で使用に注意してください[T]unapply)、

trait StringDecoder[A] {
  def fromString(string: String): Option[A]
}

object ExampleExtractor {
  def unapply[T](a: String)(implicit evidence: StringDecoder[T]): Option[T] = {
    evidence.fromString(a)
  }
}    

object Example extends App {          

 implicit val stringDecoder = new StringDecoder[String] {
    def fromString(string: String): Option[String] = Some(string)
  }

  implicit val intDecoder = new StringDecoder[Int] {
    def fromString(string: String): Option[Int] = Some(string.charAt(0).toInt)
  }

  val result = "hello" match {
    case ExampleExtractor[String](x) => x     // <- type hint barfs
  }
  println(result)
}

しかし、次のコンパイルエラーが発生します

Error: (25, 10) not found: type ExampleExtractor case ExampleExtractor[String] (x) => x ^

スコープ内に1 つだけ暗黙的valであり、型ヒント (以下を参照) をドロップすると問題なく動作しますが、それではオブジェクトが無効になります。

object Example extends App {

  implicit val intDecoder = new StringDecoder[Int] {
    def fromString(string: String): Option[Int] = Some(string.charAt(0).toInt)
  }

  val result = "hello" match {
    case ExampleExtractor(x) => x
  }
  println(result)
}
4

1 に答える 1

3

型付き文字列デコーダーの変形は有望に見えます:

trait StringDecoder[A] { 
   def fromString(s: String): Option[A] 
}

class ExampleExtractor[T](ev: StringDecoder[T]) {
   def unapply(s: String) = ev.fromString(s)
}
object ExampleExtractor { 
   def apply[A](implicit ev: StringDecoder[A]) = new ExampleExtractor(ev) 
}

それから

implicit val intDecoder = new StringDecoder[Int] { 
    def fromString(s: String) = scala.util.Try {
        Integer.parseInt(s)
    }.toOption
}

val asInt = ExampleExtractor[Int]
val asInt(Nb) = "1111"

あなたが求めているものを生み出すようです。1 つの問題が残っています。

val ExampleExtractor[Int](nB) = "1111"

コンパイラがクラッシュします (少なくとも 2.10.3 SBT Scala コンソール内で)。

于 2015-09-08T09:52:59.847 に答える