Scala:如何在trait中添加依赖于类型的方法?
发布时间:2020-12-16 18:22:21 所属栏目:安全 来源:网络整理
导读:我有以下想法: trait Generator[A] { def generate: Stream[A] // (1) If A : Int def +(other: Generator[Int]): Generator[Int] = ( CustomGeneratorInt( (this.asInstanceOf[Generator[Int]].generate,other.generate) .zipped .map(_ + _)) ) // (2) If
我有以下想法:
trait Generator[A] { def generate: Stream[A] // (1) If A <: Int def +(other: Generator[Int]): Generator[Int] = ( CustomGeneratorInt( (this.asInstanceOf[Generator[Int]].generate,other.generate) .zipped .map(_ + _)) ) // (2) If A <: Boolean def &&(other: Generator[Boolean]): Generator[Boolean] = ... } case class CustomGeneratorInt(val generate: Stream[Int]) extends Generator[Int] case class ConstantInt(i: Int) extends Generator[Int] { def generate = Stream(i) } case class ConstantBool(i: Boolean) extends Generator[Boolean] { def generate = Stream(i) } case class GeneratorRandomInt(i: Int) extends Generator[Int] { def generate = ... } ConstantInt(1) + ConstantInt(2) // (3) ok ConstantBool(true) && ConstantBool(false) // (4) ok ConstantInt(1) + ConstantBool(false) // (5) ConstantBool(true) + ConstantInt(1) // (6) compiles but it's bad ConstantBool(true) && ConstantInt(1) // (7) ConstantInt(1) && ConstantBool(true) // (8) compiles but it's bad 如果它们没有应用于正确的方案,我希望(1)和(2)引发编译器异常.例如,虽然(6)和(8)目前编译,但他们不应该编译. (5)和(7)已经不编译了. 解决方法
您可以使用通用类型约束(请参阅
this answer)来实现您的目标:
trait Generator[A] { def generate: Stream[A] def +(other: Generator[A])(implicit evidence: A =:= Int): Generator[Int] = ??? def &&(other: Generator[A])(implicit evidence: A =:= Boolean): Generator[Boolean] = ??? } case class GeneratorInt(i: Int) extends Generator[Int] { def generate = Stream(i) } case class GeneratorBool(i: Boolean) extends Generator[Boolean] { def generate = Stream(i) } GeneratorInt(1) + GeneratorInt(2) // (3) ok GeneratorBool(true) && GeneratorBool(false) // (4) ok GeneratorInt(1) + GeneratorBool(false) // (5) type mismatch GeneratorBool(true) + GeneratorInt(1) // (6) type mismatch GeneratorBool(true) && GeneratorInt(1) // (7) type mismatch GeneratorInt(1) && GeneratorBool(true) // (8) type mismatch (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |