0

I wrote the following code but I'm getting errors because it isn't the right way to implement it in Scala. I'm new to Scala, so if you can tell me how exactly I can define nextObj so that it can later get initialized it will be great.

    trait  myInterface[A]
  {
  }
class MyClass[A] extends myInterface[A]{
  var myVal:A=_
  var nextObj:MyClass[Any]=_

  def mapNextObj[B](map_func:A=>B):myInterface[B]={
    nextObj=new MyClass[B]()
    nextObj.myVal=map_func(myVal)
    nextObj
  }

  def cleanAllLinkedObjects():Unit={
    nextObj.cleanAllLinkedObjects()
    myVal=_
  }

I want to be able to initialize the nextObj in the mapNextObj func. In addition, I need to keep nextObj as a data member because I want to cleanAll objects in some point while I have in my main only the first Obj.

I used just an example, but I'm trying to get the idea of how I can do something like that in Scala.

The issues I'm facing:

  1. I can't initialize nextObj in mapNextObj as MyClass[B]. Getting : required MyClass[Any] Found : MyClass[B]

  2. Same error as in 1 but regarding return code (required MyClass[B] found MyClass[Any]

halfer
  • 19,824
  • 17
  • 99
  • 186
JeyJ
  • 3,582
  • 4
  • 35
  • 83
  • Please show actual code and error. There are a few patent errors here. Which do you mean? – som-snytt Jan 08 '20 at 20:50
  • @som-snytt - add that info in the comment – JeyJ Jan 08 '20 at 20:56
  • 2
    This kind of mutable design is not idiomatic in **Scala** and you will notice that they are hard to write. It would be better if you can explain what do you want to design, how that class will be sued, which problem does it solves. – Luis Miguel Mejía Suárez Jan 08 '20 at 21:09
  • Basically in continue to https://stackoverflow.com/questions/59631317/scala-stream-and-executioncontext-issue?noredirect=1#comment105457982_59631317 I just want to kill all threads that I run, but if I wont save the nextObj I dont have access to its threads.. I thought that it will be much easier to focus on the example that I wrote in this post.. – JeyJ Jan 08 '20 at 21:15
  • @jwvh - it isnt the issue here, I updated it because u are right. But my main issue is different.. – JeyJ Jan 08 '20 at 21:29
  • to follow up, I think it's ok to be non-idiomatic while you're working through a design and trying to understand some basic semantics. Edit: yeah, maybe your assignment requires an idiomatic solution. – som-snytt Jan 09 '20 at 05:12
  • @som-snytt any idea how can I fix the error i'm getting for : nextObj=new MyClass[B]() – JeyJ Jan 09 '20 at 08:49
  • define class MyClass[+A] if MyClass[B] is a MyClass[Any]. Oh, or make it `private[this] var nextObj` to ignore variance maybe. I never do that, and they removed the escape hatch from scala 3. – som-snytt Jan 09 '20 at 17:05

1 Answers1

0

I changed the data type of nextObj to be myInterface. That solved it for me

JeyJ
  • 3,582
  • 4
  • 35
  • 83