marmistrz
marmistrz

Reputation: 6404

Create a Scala function without explicitly declaring the types

I'd like to create a simple function:

def sum(a,b) = a + b

But then it won't compile, I have to do

def sum(a:Int, b:Int) : Int = a + b

Which is much longer to code and type-bound. Is it possible to do it without specifying the type, just as I'd do in OCaml:

let sum x y = x + y

Upvotes: 2

Views: 46

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37842

In Scala, you can omit a function's return type, but not the argument types:

def sum(a:Int, b:Int) = a + b // return type inferred to be Int

For more about Scala type inference, see: http://docs.scala-lang.org/tutorials/tour/local-type-inference.html

Upvotes: 5

Related Questions