0

I'm trying to achieve method overloading within an object by declaring function with val, but it doesn't work as expected (changing val to def makes no difference):

object B {
  val p: (=> Unit) = println(1)
  val p: (Int => Unit) = (i) => println(i) # p is already defined in the scope
}

But if I use def everything works well:

object A {
  def p() = println(1)
  def p(i: Int) = println(i)
}

The reason why I'm using the first way is I already have a type alias for a function (let's say type printit = Int => Unit, and I'm not sure how to use that printit type with def.

Any help will be really appreciated! Thank you!

  • If I invoke `B.p`, what should happen? With a method, it's clear: count the arguments, look at their type, determine which method should be called. How is it supposed to work with `val`? You kind-of answered your own question in the last edit.... – Andrey Tyukin Jul 20 '18 at 21:36
  • That makes sense. So is there anyway that I can create a method that takes an `Int` and returns `Unit` by just using the `printit` type? – Bubble Bubble Bubble Gut Jul 20 '18 at 21:42
  • You can create a `def`/`val` that returns a function value of type `printit`, but each such `def`/`val` must have its own unique signature. `val p: X` and `val p: Y` cannot be distinguished by their inputs, because they take no inputs in the first place. – Andrey Tyukin Jul 20 '18 at 21:44
  • https://stackoverflow.com/a/2530007/1151929 – sarveshseri Jul 21 '18 at 04:49

0 Answers0