Hello,
I have the following wrapper class:
sealed trait Val[V] {
val v: V
override def toString: String = s"Val($v)"
override def equals(obj: scala.Any): Boolean = {
if (obj.isInstanceOf[Val[V]]){
val other = obj.asInstanceOf[Val[V]]
v.equals(other.v)
}
else
false
}
}
object Val {
def apply[T](e:T): Val[T] = new Val[T] {
override val v:T = e
}
}
And I can implicitly wrap and unwrap using these:
implicit def pack[A](s:A) : Val[A] = new Val[A] {
override val v: A = s
}
implicit def unpack[T](t:Val[_]): Either[String,T] = {
try {
val v = t.v.asInstanceOf[T]
Right(v)
} catch {
case e: Exception => Left(e.getMessage)
}
}
So currently I can pack/unpack and use Val
so:
val v1: Val[String] = "100.0"
val v2: Val[Double] = 200.0
val v3: Val[Int] = 300
val s1:Either[String,String] = v1
val s2:Either[String,Double] = v2
val s3:Either[String,Int] = v3
val r: Either[String, Double] = for {
t <- s1
t1 = t.toDouble
t2 <- s2
t3 <- s3
ts = t1 + t2 + t3
} yield ts
r shouldBe 'right
r.right.get shouldBe 600.0
However I would like to use it so:
val ri = for {
v1t:String <- v1
v1d = v1t.toDouble
v2d:Double <- v2
v3d:Int <- v3
ts = v1d + v2d + v3d
} yield ts
ri shouldBe 'right
ri.right.get shouldBe 600.0
Now this does not compile because Val lacks the withFilter
member.
I therefore need to implement the scala.collection.generic.FilterMonadic
interface. I have made several attempts and have also looked at Scala’s
Option
in order to use that as a reference. However I have no success.
Can anyone give me hints or point me to an example that
implements these so that the above for-comprehension works
(assuming this is possible)?
def map[R](f: V => R): R = f(v)
def flatMap[R](f: V => Val[R]): Val[R] = f(v)
def filter(p: V => Boolean): ??? = ???
def withFilter(p: V => Boolean): ??? = ???
TIA