oopocamlinstance-variablesunbound

Instance variable declared as unbound


I am trying to make a class with two parameters and a simple get method. But I am getting an error :Some type variables are unbound in this type. So my question is what am I doing wrong?

class basket num_apples num_bananas= 
  object
    val mutable apples = num_apples 
    val mutable bananas = num_bananas 
    method get_a= num_apples (*I suppose it has something to do with this value here*) 
      
  end ;; 

Solution

  • The full error message is:

    Error: Some type variables are unbound in this type:
             class basket :
               'a ->
               'b ->
               object
                 val mutable apples : 'a
                 val mutable bananas : 'b
                 method get_a : 'a
               end
           The method get_a has type 'a where 'a is unbound
    

    Where you can see that the type variables it refers to are 'a and 'b. What it means is that it doesn't know what type these arguments have, because they're not used in any way that suggests their actual type. They could be anything, and if the type variables were parameterized on the class type the compiler would happily accept that. In this case it's fairly obvious that the arguments should be ints, however, so just adding a type annotation for that somewhere in the definition should suffice. Here I've added type annotations to the instance variables:

    class basket num_apples num_bananas =
      object
        val mutable apples: int = num_apples 
        val mutable bananas: int = num_bananas 
        method get_a = num_apples
      end ;;