2

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
8
  • Scala is a statically typed language. How would you expect the compiler to infer the type of a and b? the + operator can be applied to any two types. Commented May 4, 2016 at 13:01
  • 1
    @YuvalItzchakov Well, since it's statically typed, I would actually expect it to infer exactly that ;) Seriously, that this doesn't work is just an artifact of Scala's specific type system, while in other languages like Haskell, which infer polymorphic types, sum a b = a + b would get a type like forall a. Num a => a -> a -> a. This can be done because there we have no subtying and type classes are closed, which is both not the case in Scala. Commented May 4, 2016 at 13:10
  • @phg But how would type inference pick up that you're referring to two Int's and not two String's? Commented May 4, 2016 at 13:11
  • Well, OCaml is statically typed, and doesn't complain. It's just the same code which can be applied to many types Commented May 4, 2016 at 13:11
  • 2
    @YuvalItzchakov The point is that Haskell doesn't fix the concrete types at that point. The inferred type is fully polymorphic and can be applied to everything, as long as there exists an instance of the Num typeclass. In Scala terms, something like sum[T](a: T, b: T)(implicit plusable: { def +(T, T): T }). If you later happen to apply sum to an Int, then that's ok, because that's subsumed under the polymorphic type. Commented May 4, 2016 at 13:17

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.