strangelights.com

Main F# Site

Edit Edit
Print Print
Recent Changes Recent Changes
Subscriptions Subscriptions
Lost and Found Lost and Found
Find References Find References
Rename Rename
Search
List all versions List all versions
Objects And All That
.

Check out the formatting tips on the right for help formatting and making links.

Summary

Objects without classes: Object Expressions

Most object implementations do not require you to write a new class. You can use ObjectExpressions instead.

Classes Implementing Interfaces

Interface implementations are specified as follows. This allows for the implementation of multiple interfaces where member names overlap.

 type Foo =
  interface 
      abstract fun1 : int -> int
      abstract fun2 : int -> int
  end


 type Bar =
  class 
      val store : int
      interface Foo with
        override self.fun1(x) = self.store
        override self.fun2(x) = self.store+1
      end
      new(x) = { store = x }
  end

Interface implementations can be specified for record, union and class types.

 type Bar2 = 
  | A of int 
  | B of string
  with
      interface Foo with
        member self.fun1(x) = match self with A n -> n | B s -> String.length s
        member self.fun2(x) = x+1
      end
  end

Interfaces define their member methods by types by their signature see InterfacesAndFSharpTypes for more details.

Declaring Virtual Members

A virtual member is a new dispatch slot for a class of objects combined with a default implementation for invocations of the slot. Use "abstract" to declare the slot combined with "default" to declare the default implementation, e.g.

 class
   ...
   abstract MyMethod : string * string -> int
   default MyMethod(s1,s2) = length(s1) + length(s2)
   ...
 end

In this context "default" is a synonym for "override", though "default" should be used to provide a first value, and "override" to replace a value. We deliberately separated the definition of "abstract dispatch slots" from the provision of default values for those slots. This is because of

  1. type inference - inferring most general types for dispatch slots based on default definitions does not seem a good idea when one of the main reasons for the object model is interoperability
  2. long term plans to support mixins, where mixins could, for example, provide defaults for functionality without defining new abstract slots
  3. a general feeling that OO-style dispatch needs enough thought-before-use that writing a type won't do anyone any harm.
Welcome to F Sharp Wiki, view the HomePage

This site supports the new NoFollow anti-spam initiative.

Recent Topics

Copyright 2005, Robert Pickering (Others where credited) | Terms of Use