How to retrieve derived classes as is from a Map? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Difference between object and class in Scalatype parametrization or structural subtyping orHow could I overload trait variableOverriding Add Method of Scala Map with TraitA case class as a “wrapper” class for a collection. What about map/foldLeft/Scala: Is it possible to override val's in the sub-class's constructor?Scala immutable container class extended with mixinsScala trait function: return instance of derived typeMap key not found error despite using option classesCreate proper late initialization of an abstract val in trait

Pointing to problems without suggesting solutions

Determine whether an integer is a palindrome

My mentor says to set image to Fine instead of RAW — how is this different from JPG?

Why do C and C++ allow the expression (int) + 4*5?

Is a copyright notice with a non-existent name be invalid?

Table formatting with tabularx?

Vertical ranges of Column Plots in 12

Does the main washing effect of soap come from foam?

Russian equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

Is the Mordenkainen's Sword spell underpowered?

How could a hydrazine and N2O4 cloud (or it's reactants) show up in weather radar?

Problem with display of presentation

How does TikZ render an arc?

Improvising over quartal voicings

3D Masyu - A Die

Statistical analysis applied to methods coming out of Machine Learning

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

Flight departed from the gate 5 min before scheduled departure time. Refund options

.bashrc alias for a command with fixed second parameter

How to achieve cat-like agility?

Random body shuffle every night—can we still function?

Why complex landing gears are used instead of simple, reliable and light weight muscle wire or shape memory alloys?

Fit odd number of triplets in a measure?

Why not use the yoke to control yaw, as well as pitch and roll?



How to retrieve derived classes as is from a Map?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Difference between object and class in Scalatype parametrization or structural subtyping orHow could I overload trait variableOverriding Add Method of Scala Map with TraitA case class as a “wrapper” class for a collection. What about map/foldLeft/Scala: Is it possible to override val's in the sub-class's constructor?Scala immutable container class extended with mixinsScala trait function: return instance of derived typeMap key not found error despite using option classesCreate proper late initialization of an abstract val in trait



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have to retrieve Derived class objects stored in a Map given the respective class name as key.



As show below



trait Caluclator
class PreScoreCalculator(data:Seq[Int]) extends Caluclator
class BenchMarkCalculator(data:Seq[Int]) extends Caluclator


val calculatorsLookUp:Map[String, Calculator] = Map[String, Calculator](
"PreScore" -> new PreScoreCalculator,
"BenchMark" -> new BenchMarkCalculator
)


Given key name i need to get respective object/instance from Map



def getCalculatorByOperationName(operation:String) : Option[ Calculator] = 
calculatorsLookUp.get(operation)



I am calling as below



 val calcName = "PreScore"

val opt = getCalculatorByOperationName(calcName)

if(opt.isInstanceOf[PreScoreCalculator] ) /// this is coming as false
calculationController.calculate(opt) // this is not being executed.


Expect :
Execute calculationController.calculate(opt)



Error :
Above if condition is false hence not getting executed.



So how to handle this problem?



How to handle below i.e. default constructor objects ?



class PreScoreCalculator(data:Seq[Int]) extends Caluclator









share|improve this question






























    1















    I have to retrieve Derived class objects stored in a Map given the respective class name as key.



    As show below



    trait Caluclator
    class PreScoreCalculator(data:Seq[Int]) extends Caluclator
    class BenchMarkCalculator(data:Seq[Int]) extends Caluclator


    val calculatorsLookUp:Map[String, Calculator] = Map[String, Calculator](
    "PreScore" -> new PreScoreCalculator,
    "BenchMark" -> new BenchMarkCalculator
    )


    Given key name i need to get respective object/instance from Map



    def getCalculatorByOperationName(operation:String) : Option[ Calculator] = 
    calculatorsLookUp.get(operation)



    I am calling as below



     val calcName = "PreScore"

    val opt = getCalculatorByOperationName(calcName)

    if(opt.isInstanceOf[PreScoreCalculator] ) /// this is coming as false
    calculationController.calculate(opt) // this is not being executed.


    Expect :
    Execute calculationController.calculate(opt)



    Error :
    Above if condition is false hence not getting executed.



    So how to handle this problem?



    How to handle below i.e. default constructor objects ?



    class PreScoreCalculator(data:Seq[Int]) extends Caluclator









    share|improve this question


























      1












      1








      1








      I have to retrieve Derived class objects stored in a Map given the respective class name as key.



      As show below



      trait Caluclator
      class PreScoreCalculator(data:Seq[Int]) extends Caluclator
      class BenchMarkCalculator(data:Seq[Int]) extends Caluclator


      val calculatorsLookUp:Map[String, Calculator] = Map[String, Calculator](
      "PreScore" -> new PreScoreCalculator,
      "BenchMark" -> new BenchMarkCalculator
      )


      Given key name i need to get respective object/instance from Map



      def getCalculatorByOperationName(operation:String) : Option[ Calculator] = 
      calculatorsLookUp.get(operation)



      I am calling as below



       val calcName = "PreScore"

      val opt = getCalculatorByOperationName(calcName)

      if(opt.isInstanceOf[PreScoreCalculator] ) /// this is coming as false
      calculationController.calculate(opt) // this is not being executed.


      Expect :
      Execute calculationController.calculate(opt)



      Error :
      Above if condition is false hence not getting executed.



      So how to handle this problem?



      How to handle below i.e. default constructor objects ?



      class PreScoreCalculator(data:Seq[Int]) extends Caluclator









      share|improve this question
















      I have to retrieve Derived class objects stored in a Map given the respective class name as key.



      As show below



      trait Caluclator
      class PreScoreCalculator(data:Seq[Int]) extends Caluclator
      class BenchMarkCalculator(data:Seq[Int]) extends Caluclator


      val calculatorsLookUp:Map[String, Calculator] = Map[String, Calculator](
      "PreScore" -> new PreScoreCalculator,
      "BenchMark" -> new BenchMarkCalculator
      )


      Given key name i need to get respective object/instance from Map



      def getCalculatorByOperationName(operation:String) : Option[ Calculator] = 
      calculatorsLookUp.get(operation)



      I am calling as below



       val calcName = "PreScore"

      val opt = getCalculatorByOperationName(calcName)

      if(opt.isInstanceOf[PreScoreCalculator] ) /// this is coming as false
      calculationController.calculate(opt) // this is not being executed.


      Expect :
      Execute calculationController.calculate(opt)



      Error :
      Above if condition is false hence not getting executed.



      So how to handle this problem?



      How to handle below i.e. default constructor objects ?



      class PreScoreCalculator(data:Seq[Int]) extends Caluclator






      scala databricks






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 7:05







      Shyam

















      asked Mar 22 at 13:01









      ShyamShyam

      328




      328






















          3 Answers
          3






          active

          oldest

          votes


















          1














          You should not call isInstanceOf & asInstanceOf manually, because that is basically throwing the compiler away.

          You should use pattern matching instead:



          opt match 
          case Some(c: PreScoreCalculator) => calculationController.calculate(c)
          ... // Other calculators.
          case None => println("Calculator not found.")



          Note: This is basically the same Ichoran and I already said in gitter, I am just leaving this here for the record.






          share|improve this answer























          • Miguel Mejia Suarez Thank you so much for more clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 6:58











          • @Miguel Mejia Suarez Can you please recommand good book for learning scala application design and best practices ?

            – Shyam
            Mar 25 at 7:00











          • @Shyam Can you elaborate that please? Do you need to extract that Seq too? PS: Can you modify the code of the Calculators, or those are out of you control?

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:41






          • 1





            @Shyam Technically speaking, SO is not a place to ask for books / courses recommendations... but, since it is a comment and not a question itself, I guess is not too bad. Of course everyone will think different, but I really liked "Programming in Scala" (Book) & "Functional Programming in Scala" (Coursera Specialization) for starting. And after a while (most people recommend one year of experience) start learning about FP "Scala with Cats" is great to begin with.

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:49











          • thank you so much

            – Shyam
            Mar 26 at 13:47


















          2














          You have a small bug:



          opt is of type Option[Calculator]



          In Scala a nice way to handle that is pattern matching:



          opt match 
          case Some(calculator: PreScoreCalculator) =>
          calculationController.calculate(calculator)
          case _ => // nothing to do



          Or do it in a more declarative way:



           opt.filter(_.isInstanceOf[PreScoreCalculator])
          .foreach(calculationController.calculate)


          However the use of instanceOf is a bit of an anti pattern.



          As a tip:



          Use println(opt.getClass) > then you see the class.






          share|improve this answer

























          • thank you for prompt reply , sorry this execute all the time even if the key is not PreScore. And println(opt.getClass) gives "class scala.Some"

            – Shyam
            Mar 22 at 14:14











          • you are right sorry - I fixed my answer and tested now both cases;)

            – pme
            Mar 22 at 15:02











          • thank you so much , why are using foreach here ? What am I iterating here ?

            – Shyam
            Mar 25 at 6:59






          • 1





            opt is of type Option[Calculator]. If you want do something with it you have to unwrap it, to use it > foreach does that - check the API of Option.

            – pme
            Mar 25 at 7:27












          • Thank you for clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 7:34


















          1














          The problem here is on



          val opt = getCalculatorByOperationName(calcName)


          because it will return Option[Calculator] not Calculator. Now it will look like this..



          if(opt.map(_.isInstanceOf[PreScoreCalculator]).getOrElse(false))
          calculationController.calculate(opt.get)


          Hope it helps.






          share|improve this answer

























          • thank you , may i know why are you using .map here ? if it is not .isInstanceOf[PreScoreCalculator] returns false if the key is not "PreScore" right ? why do we need .getOrElse(false) ???

            – Shyam
            Mar 22 at 14:15






          • 1





            Okay. First, result of the opt is always Option[Calculator] and Scala’s Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). In case the result is None then it will go to .getOrElse(false) so it is safe.

            – Rex
            Mar 22 at 23:34












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55300204%2fhow-to-retrieve-derived-classes-as-is-from-a-map%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You should not call isInstanceOf & asInstanceOf manually, because that is basically throwing the compiler away.

          You should use pattern matching instead:



          opt match 
          case Some(c: PreScoreCalculator) => calculationController.calculate(c)
          ... // Other calculators.
          case None => println("Calculator not found.")



          Note: This is basically the same Ichoran and I already said in gitter, I am just leaving this here for the record.






          share|improve this answer























          • Miguel Mejia Suarez Thank you so much for more clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 6:58











          • @Miguel Mejia Suarez Can you please recommand good book for learning scala application design and best practices ?

            – Shyam
            Mar 25 at 7:00











          • @Shyam Can you elaborate that please? Do you need to extract that Seq too? PS: Can you modify the code of the Calculators, or those are out of you control?

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:41






          • 1





            @Shyam Technically speaking, SO is not a place to ask for books / courses recommendations... but, since it is a comment and not a question itself, I guess is not too bad. Of course everyone will think different, but I really liked "Programming in Scala" (Book) & "Functional Programming in Scala" (Coursera Specialization) for starting. And after a while (most people recommend one year of experience) start learning about FP "Scala with Cats" is great to begin with.

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:49











          • thank you so much

            – Shyam
            Mar 26 at 13:47















          1














          You should not call isInstanceOf & asInstanceOf manually, because that is basically throwing the compiler away.

          You should use pattern matching instead:



          opt match 
          case Some(c: PreScoreCalculator) => calculationController.calculate(c)
          ... // Other calculators.
          case None => println("Calculator not found.")



          Note: This is basically the same Ichoran and I already said in gitter, I am just leaving this here for the record.






          share|improve this answer























          • Miguel Mejia Suarez Thank you so much for more clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 6:58











          • @Miguel Mejia Suarez Can you please recommand good book for learning scala application design and best practices ?

            – Shyam
            Mar 25 at 7:00











          • @Shyam Can you elaborate that please? Do you need to extract that Seq too? PS: Can you modify the code of the Calculators, or those are out of you control?

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:41






          • 1





            @Shyam Technically speaking, SO is not a place to ask for books / courses recommendations... but, since it is a comment and not a question itself, I guess is not too bad. Of course everyone will think different, but I really liked "Programming in Scala" (Book) & "Functional Programming in Scala" (Coursera Specialization) for starting. And after a while (most people recommend one year of experience) start learning about FP "Scala with Cats" is great to begin with.

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:49











          • thank you so much

            – Shyam
            Mar 26 at 13:47













          1












          1








          1







          You should not call isInstanceOf & asInstanceOf manually, because that is basically throwing the compiler away.

          You should use pattern matching instead:



          opt match 
          case Some(c: PreScoreCalculator) => calculationController.calculate(c)
          ... // Other calculators.
          case None => println("Calculator not found.")



          Note: This is basically the same Ichoran and I already said in gitter, I am just leaving this here for the record.






          share|improve this answer













          You should not call isInstanceOf & asInstanceOf manually, because that is basically throwing the compiler away.

          You should use pattern matching instead:



          opt match 
          case Some(c: PreScoreCalculator) => calculationController.calculate(c)
          ... // Other calculators.
          case None => println("Calculator not found.")



          Note: This is basically the same Ichoran and I already said in gitter, I am just leaving this here for the record.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 22 at 15:42









          Luis Miguel Mejía SuárezLuis Miguel Mejía Suárez

          2,86421023




          2,86421023












          • Miguel Mejia Suarez Thank you so much for more clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 6:58











          • @Miguel Mejia Suarez Can you please recommand good book for learning scala application design and best practices ?

            – Shyam
            Mar 25 at 7:00











          • @Shyam Can you elaborate that please? Do you need to extract that Seq too? PS: Can you modify the code of the Calculators, or those are out of you control?

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:41






          • 1





            @Shyam Technically speaking, SO is not a place to ask for books / courses recommendations... but, since it is a comment and not a question itself, I guess is not too bad. Of course everyone will think different, but I really liked "Programming in Scala" (Book) & "Functional Programming in Scala" (Coursera Specialization) for starting. And after a while (most people recommend one year of experience) start learning about FP "Scala with Cats" is great to begin with.

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:49











          • thank you so much

            – Shyam
            Mar 26 at 13:47

















          • Miguel Mejia Suarez Thank you so much for more clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 6:58











          • @Miguel Mejia Suarez Can you please recommand good book for learning scala application design and best practices ?

            – Shyam
            Mar 25 at 7:00











          • @Shyam Can you elaborate that please? Do you need to extract that Seq too? PS: Can you modify the code of the Calculators, or those are out of you control?

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:41






          • 1





            @Shyam Technically speaking, SO is not a place to ask for books / courses recommendations... but, since it is a comment and not a question itself, I guess is not too bad. Of course everyone will think different, but I really liked "Programming in Scala" (Book) & "Functional Programming in Scala" (Coursera Specialization) for starting. And after a while (most people recommend one year of experience) start learning about FP "Scala with Cats" is great to begin with.

            – Luis Miguel Mejía Suárez
            Mar 25 at 15:49











          • thank you so much

            – Shyam
            Mar 26 at 13:47
















          Miguel Mejia Suarez Thank you so much for more clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

          – Shyam
          Mar 25 at 6:58





          Miguel Mejia Suarez Thank you so much for more clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

          – Shyam
          Mar 25 at 6:58













          @Miguel Mejia Suarez Can you please recommand good book for learning scala application design and best practices ?

          – Shyam
          Mar 25 at 7:00





          @Miguel Mejia Suarez Can you please recommand good book for learning scala application design and best practices ?

          – Shyam
          Mar 25 at 7:00













          @Shyam Can you elaborate that please? Do you need to extract that Seq too? PS: Can you modify the code of the Calculators, or those are out of you control?

          – Luis Miguel Mejía Suárez
          Mar 25 at 15:41





          @Shyam Can you elaborate that please? Do you need to extract that Seq too? PS: Can you modify the code of the Calculators, or those are out of you control?

          – Luis Miguel Mejía Suárez
          Mar 25 at 15:41




          1




          1





          @Shyam Technically speaking, SO is not a place to ask for books / courses recommendations... but, since it is a comment and not a question itself, I guess is not too bad. Of course everyone will think different, but I really liked "Programming in Scala" (Book) & "Functional Programming in Scala" (Coursera Specialization) for starting. And after a while (most people recommend one year of experience) start learning about FP "Scala with Cats" is great to begin with.

          – Luis Miguel Mejía Suárez
          Mar 25 at 15:49





          @Shyam Technically speaking, SO is not a place to ask for books / courses recommendations... but, since it is a comment and not a question itself, I guess is not too bad. Of course everyone will think different, but I really liked "Programming in Scala" (Book) & "Functional Programming in Scala" (Coursera Specialization) for starting. And after a while (most people recommend one year of experience) start learning about FP "Scala with Cats" is great to begin with.

          – Luis Miguel Mejía Suárez
          Mar 25 at 15:49













          thank you so much

          – Shyam
          Mar 26 at 13:47





          thank you so much

          – Shyam
          Mar 26 at 13:47













          2














          You have a small bug:



          opt is of type Option[Calculator]



          In Scala a nice way to handle that is pattern matching:



          opt match 
          case Some(calculator: PreScoreCalculator) =>
          calculationController.calculate(calculator)
          case _ => // nothing to do



          Or do it in a more declarative way:



           opt.filter(_.isInstanceOf[PreScoreCalculator])
          .foreach(calculationController.calculate)


          However the use of instanceOf is a bit of an anti pattern.



          As a tip:



          Use println(opt.getClass) > then you see the class.






          share|improve this answer

























          • thank you for prompt reply , sorry this execute all the time even if the key is not PreScore. And println(opt.getClass) gives "class scala.Some"

            – Shyam
            Mar 22 at 14:14











          • you are right sorry - I fixed my answer and tested now both cases;)

            – pme
            Mar 22 at 15:02











          • thank you so much , why are using foreach here ? What am I iterating here ?

            – Shyam
            Mar 25 at 6:59






          • 1





            opt is of type Option[Calculator]. If you want do something with it you have to unwrap it, to use it > foreach does that - check the API of Option.

            – pme
            Mar 25 at 7:27












          • Thank you for clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 7:34















          2














          You have a small bug:



          opt is of type Option[Calculator]



          In Scala a nice way to handle that is pattern matching:



          opt match 
          case Some(calculator: PreScoreCalculator) =>
          calculationController.calculate(calculator)
          case _ => // nothing to do



          Or do it in a more declarative way:



           opt.filter(_.isInstanceOf[PreScoreCalculator])
          .foreach(calculationController.calculate)


          However the use of instanceOf is a bit of an anti pattern.



          As a tip:



          Use println(opt.getClass) > then you see the class.






          share|improve this answer

























          • thank you for prompt reply , sorry this execute all the time even if the key is not PreScore. And println(opt.getClass) gives "class scala.Some"

            – Shyam
            Mar 22 at 14:14











          • you are right sorry - I fixed my answer and tested now both cases;)

            – pme
            Mar 22 at 15:02











          • thank you so much , why are using foreach here ? What am I iterating here ?

            – Shyam
            Mar 25 at 6:59






          • 1





            opt is of type Option[Calculator]. If you want do something with it you have to unwrap it, to use it > foreach does that - check the API of Option.

            – pme
            Mar 25 at 7:27












          • Thank you for clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 7:34













          2












          2








          2







          You have a small bug:



          opt is of type Option[Calculator]



          In Scala a nice way to handle that is pattern matching:



          opt match 
          case Some(calculator: PreScoreCalculator) =>
          calculationController.calculate(calculator)
          case _ => // nothing to do



          Or do it in a more declarative way:



           opt.filter(_.isInstanceOf[PreScoreCalculator])
          .foreach(calculationController.calculate)


          However the use of instanceOf is a bit of an anti pattern.



          As a tip:



          Use println(opt.getClass) > then you see the class.






          share|improve this answer















          You have a small bug:



          opt is of type Option[Calculator]



          In Scala a nice way to handle that is pattern matching:



          opt match 
          case Some(calculator: PreScoreCalculator) =>
          calculationController.calculate(calculator)
          case _ => // nothing to do



          Or do it in a more declarative way:



           opt.filter(_.isInstanceOf[PreScoreCalculator])
          .foreach(calculationController.calculate)


          However the use of instanceOf is a bit of an anti pattern.



          As a tip:



          Use println(opt.getClass) > then you see the class.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 22 at 15:07

























          answered Mar 22 at 13:28









          pmepme

          3,62011933




          3,62011933












          • thank you for prompt reply , sorry this execute all the time even if the key is not PreScore. And println(opt.getClass) gives "class scala.Some"

            – Shyam
            Mar 22 at 14:14











          • you are right sorry - I fixed my answer and tested now both cases;)

            – pme
            Mar 22 at 15:02











          • thank you so much , why are using foreach here ? What am I iterating here ?

            – Shyam
            Mar 25 at 6:59






          • 1





            opt is of type Option[Calculator]. If you want do something with it you have to unwrap it, to use it > foreach does that - check the API of Option.

            – pme
            Mar 25 at 7:27












          • Thank you for clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 7:34

















          • thank you for prompt reply , sorry this execute all the time even if the key is not PreScore. And println(opt.getClass) gives "class scala.Some"

            – Shyam
            Mar 22 at 14:14











          • you are right sorry - I fixed my answer and tested now both cases;)

            – pme
            Mar 22 at 15:02











          • thank you so much , why are using foreach here ? What am I iterating here ?

            – Shyam
            Mar 25 at 6:59






          • 1





            opt is of type Option[Calculator]. If you want do something with it you have to unwrap it, to use it > foreach does that - check the API of Option.

            – pme
            Mar 25 at 7:27












          • Thank you for clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

            – Shyam
            Mar 25 at 7:34
















          thank you for prompt reply , sorry this execute all the time even if the key is not PreScore. And println(opt.getClass) gives "class scala.Some"

          – Shyam
          Mar 22 at 14:14





          thank you for prompt reply , sorry this execute all the time even if the key is not PreScore. And println(opt.getClass) gives "class scala.Some"

          – Shyam
          Mar 22 at 14:14













          you are right sorry - I fixed my answer and tested now both cases;)

          – pme
          Mar 22 at 15:02





          you are right sorry - I fixed my answer and tested now both cases;)

          – pme
          Mar 22 at 15:02













          thank you so much , why are using foreach here ? What am I iterating here ?

          – Shyam
          Mar 25 at 6:59





          thank you so much , why are using foreach here ? What am I iterating here ?

          – Shyam
          Mar 25 at 6:59




          1




          1





          opt is of type Option[Calculator]. If you want do something with it you have to unwrap it, to use it > foreach does that - check the API of Option.

          – pme
          Mar 25 at 7:27






          opt is of type Option[Calculator]. If you want do something with it you have to unwrap it, to use it > foreach does that - check the API of Option.

          – pme
          Mar 25 at 7:27














          Thank you for clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

          – Shyam
          Mar 25 at 7:34





          Thank you for clarity , if my PreScoreCalculator takes a constructor i.e. PreScoreCalculator(data:Seq[Int]) how can handle it , in the above scenario ?

          – Shyam
          Mar 25 at 7:34











          1














          The problem here is on



          val opt = getCalculatorByOperationName(calcName)


          because it will return Option[Calculator] not Calculator. Now it will look like this..



          if(opt.map(_.isInstanceOf[PreScoreCalculator]).getOrElse(false))
          calculationController.calculate(opt.get)


          Hope it helps.






          share|improve this answer

























          • thank you , may i know why are you using .map here ? if it is not .isInstanceOf[PreScoreCalculator] returns false if the key is not "PreScore" right ? why do we need .getOrElse(false) ???

            – Shyam
            Mar 22 at 14:15






          • 1





            Okay. First, result of the opt is always Option[Calculator] and Scala’s Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). In case the result is None then it will go to .getOrElse(false) so it is safe.

            – Rex
            Mar 22 at 23:34
















          1














          The problem here is on



          val opt = getCalculatorByOperationName(calcName)


          because it will return Option[Calculator] not Calculator. Now it will look like this..



          if(opt.map(_.isInstanceOf[PreScoreCalculator]).getOrElse(false))
          calculationController.calculate(opt.get)


          Hope it helps.






          share|improve this answer

























          • thank you , may i know why are you using .map here ? if it is not .isInstanceOf[PreScoreCalculator] returns false if the key is not "PreScore" right ? why do we need .getOrElse(false) ???

            – Shyam
            Mar 22 at 14:15






          • 1





            Okay. First, result of the opt is always Option[Calculator] and Scala’s Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). In case the result is None then it will go to .getOrElse(false) so it is safe.

            – Rex
            Mar 22 at 23:34














          1












          1








          1







          The problem here is on



          val opt = getCalculatorByOperationName(calcName)


          because it will return Option[Calculator] not Calculator. Now it will look like this..



          if(opt.map(_.isInstanceOf[PreScoreCalculator]).getOrElse(false))
          calculationController.calculate(opt.get)


          Hope it helps.






          share|improve this answer















          The problem here is on



          val opt = getCalculatorByOperationName(calcName)


          because it will return Option[Calculator] not Calculator. Now it will look like this..



          if(opt.map(_.isInstanceOf[PreScoreCalculator]).getOrElse(false))
          calculationController.calculate(opt.get)


          Hope it helps.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 22 at 13:31

























          answered Mar 22 at 13:26









          RexRex

          36018




          36018












          • thank you , may i know why are you using .map here ? if it is not .isInstanceOf[PreScoreCalculator] returns false if the key is not "PreScore" right ? why do we need .getOrElse(false) ???

            – Shyam
            Mar 22 at 14:15






          • 1





            Okay. First, result of the opt is always Option[Calculator] and Scala’s Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). In case the result is None then it will go to .getOrElse(false) so it is safe.

            – Rex
            Mar 22 at 23:34


















          • thank you , may i know why are you using .map here ? if it is not .isInstanceOf[PreScoreCalculator] returns false if the key is not "PreScore" right ? why do we need .getOrElse(false) ???

            – Shyam
            Mar 22 at 14:15






          • 1





            Okay. First, result of the opt is always Option[Calculator] and Scala’s Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). In case the result is None then it will go to .getOrElse(false) so it is safe.

            – Rex
            Mar 22 at 23:34

















          thank you , may i know why are you using .map here ? if it is not .isInstanceOf[PreScoreCalculator] returns false if the key is not "PreScore" right ? why do we need .getOrElse(false) ???

          – Shyam
          Mar 22 at 14:15





          thank you , may i know why are you using .map here ? if it is not .isInstanceOf[PreScoreCalculator] returns false if the key is not "PreScore" right ? why do we need .getOrElse(false) ???

          – Shyam
          Mar 22 at 14:15




          1




          1





          Okay. First, result of the opt is always Option[Calculator] and Scala’s Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). In case the result is None then it will go to .getOrElse(false) so it is safe.

          – Rex
          Mar 22 at 23:34






          Okay. First, result of the opt is always Option[Calculator] and Scala’s Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). In case the result is None then it will go to .getOrElse(false) so it is safe.

          – Rex
          Mar 22 at 23:34


















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55300204%2fhow-to-retrieve-derived-classes-as-is-from-a-map%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현