user1032985
user1032985

Reputation:

Scala deep type cheking

We have a function that can returns anything:

def func: AnyRef

And we need to check if return value is a

Tuple2[String, String] 

or

List[Tuple2[String, List[String]]] 

or

List[Tuple2[String, List[Int]]] 

or anything else.

What is the right way to do that?

Upvotes: 0

Views: 245

Answers (1)

Dylan
Dylan

Reputation: 13922

If func is something that is under your control, I'd recommend creating a data type to represent the possible things that func can return, and simply return those from func. It goes against the idea of type safety to return "anything", so my answer will be to help bring back type safety.

sealed trait FuncReturnType
case class Thing1(data: (String,String)) extends FuncReturnType
case class Thing2(data: List[(String, List[String])]) extends FuncReturnType
case class Thing3(data: List[(String, List[Int])]) extends FuncReturnType
...

def func: FuncReturnType

Hopefully, the number of Thing classes is not infinite.

This way, when you call func, you can match its return value against the various thing classes, and you don't have to worry about type erasure (which you would have to do if you don't refactor in this way)

Upvotes: 1

Related Questions