4

What's the difference between type Something() and type Something in F#?

Why this snippet referenced in ASP.NET Core 1.0 F# project works:

open System
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http

type Startup() = 
    member this.Configure(app: IApplicationBuilder) =
      app.Run(fun context -> context.Response.WriteAsync("Hello from ASP.NET Core!"))

[<EntryPoint>]
let main argv = 
    let host = WebHostBuilder().UseKestrel().UseStartup<Startup>().Build()
    host.Run()
    printfn "Server finished!"
    0

but this fails:

open System
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http

type Startup = 
    member this.Configure(app: IApplicationBuilder) =
      app.Run(fun context -> context.Response.WriteAsync("Hello from ASP.NET Core!"))

[<EntryPoint>]
let main argv = 
    let host = WebHostBuilder().UseKestrel().UseStartup<Startup>().Build()
    host.Run()
    printfn "Server finished!"
    0
Community
  • 1
  • 1
  • Different types are all defined via the `type` keyword in F#, including type aliases, DUs, records, classes, etc. The different arguments will indicate what kind of type you are creating. [Intro to F# types:](http://fsharpforfunandprofit.com/series/understanding-fsharp-types.html) – s952163 Jul 10 '16 at 10:06

1 Answers1

7

You can see the difference by typing it in the F# Interactive:

type Parens() =
    member this.add10 x = x + 10

type NoParens =
    member this.add10 x = x + 10;;

Output:

type Parens =
  class
    new : unit -> Parens
    member add10 : x:int -> int
  end
type NoParens =
  class
    member add10 : x:int -> int
  end

The second class doesn't have a constructor defined. Something the compiler shouldn't allow, but does for some reason. It doesnt generate an automatic constructor like C#.

For more info check the F# for fun and profit pages on classes and interfaces. Also check out this StackOverflow post

And for future reference, when in doubt, open the F# interactive, type the two things you want to see the difference between, and compare the output. It is a powerful tool and you should use it.

Community
  • 1
  • 1
asibahi
  • 857
  • 8
  • 14