How to call a method that exists only for one of the two types in Either?

I have an array of objects of type Either [A, B]. If I know for a specific element whether it is A or B, how can I call it a method that exists for only one of two types. For instance:

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")
}

When I compile this code, the lines

case 0 => eitherArray(x).aMethod()
case 1 => eitherArray(x).bMethod()

both have the error "the value of aMethod is not a member of A [A, B]." How can i solve this?

+4
source share
3 answers

I do not know why he folddoes not receive the respect that he deserves. This may be therefore useful.

eitherArray.foreach(_.fold(_.aMethod(), _.bMethod()))
+4
source

, , , , , !

object HelloWorld {
    import scala.util.Random
   def main(args: Array[String]) {
        val random = new Random()
        val randomArray = (0 until 10).map(_ => random.nextInt(2))
        val eitherArray = randomArray.map(EitherTest.newObj) 
       (0 until 10).foreach(x => randomArray(x) match {
        case 0 => EitherTest.callmethod(eitherArray(x))
        case 1 => EitherTest.callmethod(eitherArray(x))
        case _ => println("Error!")
        })
       println("Hello, world!")
   }
}


class EitherTest 
object EitherTest {

    def callmethod(ei : Either[A,B]) = {
        ei match {
            case Left(a) => a.aMethod()
            case Right(b) => b.bMethod()
        }
    }

    def newObj(x: Int): Either[A,B] = {
        if (x == 0)
            Left(new A())
        else
            Right(new B())
    }

}

class A {
    def aMethod() = println("A")
}

class B {
    def bMethod() = println("B")
}

:

A
B
A
B
A
A
A
B
B
B
Hello, world!
+1

, , Either, - : Either.left , Either.right . , ( Either Right, left ), , map, flatMap, foreach, getOrElse ..

:

 randomArray.foreach { either =>
     either.left.foreach(_.aMethod)
     either.right.foreach(_.bMethod)
 } 

, , , , :

 randomArray.foreach { 
   case Left(a) => a.aMethod
   case Right(b) => b.bMethod
 }
0

Source: https://habr.com/ru/post/1688976/


All Articles