我有一个类型为 [A, B] 的对象数组。如果我知道特定元素是 A 还是 B,我如何调用仅存在于这两种类型之一的方法。例如:
import scala.util.Random
object EitherTest extends App {
def newObj(x: Int): Either[A,B] = {
if (x == 0)
Left(new A())
else
Right(new B())
}
val random = new Random()
val randomArray = (0 until 10).map(_ => random.nextInt(2))
val eitherArray = randomArray.map(newObj)
(0 until 10).foreach(x => randomArray(x) match {
case 0 => eitherArray(x).aMethod()
case 1 => eitherArray(x).bMethod()
case _ => println("Error!")
})
}
class A {
def aMethod() = println("A")
}
class B {
def bMethod() = println("B")
}
当我编译这段代码时,这些行
case 0 => eitherArray(x).aMethod()
case 1 => eitherArray(x).bMethod()
两者都有错误“值aMethod 不是Either[A,B] 的成员”。我该如何解决这个问题?
最佳答案
不知道为什么fold
没有得到应有的尊重。可以是所以有用。
eitherArray.foreach(_.fold(_.aMethod(), _.bMethod()))
关于scala - 如何调用仅存在于任一类型中的两种类型之一的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47191902/