0

I am beginning in scala and I need to contain a bunch of ints, and something other than a number in a List.

For example List(4,null) or List(4,"STOPSTR").

  • How would I declare a variable of type List[Int or String] (Kind of)?

  • Also, is it at all possible to declare a variable for a list that can only contain a certain string. E.g. List[Int or String=="STOPSTR"] and have it checked at compile time.

For the reasons of a challenge, I can only use Lists for this exercise, no classes, no maps, not even Arrays.

Imad
  • 2,358
  • 5
  • 26
  • 55
  • 2
    This first one will be available on **Scala 3**. The second is possible using **Refined** types _(but those are only available on external libraries)_. - In general, this seems like a code smell, **Lists** are homogeneous data structures. Can you share what is the challenge you want to solve and what have you tried? – Luis Miguel Mejía Suárez Oct 25 '19 at 16:53
  • 2
    Well I have to say that challenge is not very good, in vanilla Scala that is not possible without "hacks". Check this: https://stackoverflow.com/questions/3508077/how-to-define-type-disjunction-union-types/6312508#6312508 If you really want to do it. Curious to see the challenge if you can provided – Pedro Correia Luís Oct 25 '19 at 17:03
  • 1
    @LuisMiguelMejíaSuárez Actually, this would be a literal type (which are part of Scala 2.13), not a refined type. – Alexey Romanov Oct 25 '19 at 17:42
  • Why you need it? I use Scala about 3 year, and I doesn't need to use something like `List[Int or String]` (but sometimes I want use `Double or Int`). You can create own type for Int and String and convert both types to your type, if you need it. – Mikhail Ionkin Oct 27 '19 at 10:23

1 Answers1

2

You can do it 2 different ways:

  1. The first is using Any as the type parameter to List. The problem here though, is that it's not constrained to just Int and String types. You could add any other type to the list as well.

E.g.

List[Any](1, 2, "Three")
  1. The second is to use Either. Either has a Left and a Right type that can be different. e.g.
List[Either[Int, String]](Left(1), Left(2), Right("Three"))
Freddie
  • 871
  • 6
  • 10