Question

Has scala ability to use default parameter with duck typing?

Code below throw error: only declarations allowed here

def test(x: { def x(a:Int, b:Int = 5):Int} ) = x(1)

Was it helpful?

Solution

This is pretty cheesy:

scala> def test(x: { def x(a:Int, b:Int):Int ; def x$default$2: Int } ) = x.x(1, x.x$default$2)
warning: there were 2 feature warning(s); re-run with -feature for details
test: (x: AnyRef{def x(a: Int,b: Int): Int; def x$default$2: Int})Int

scala> val y = new { def x(a: Int, b: Int = 5): Int = a + b }
y: AnyRef{def x(a: Int,b: Int): Int; def x$default$2: Int @scala.annotation.unchecked.uncheckedVariance} = $anon$1@232864a3

scala> test(y)
res0: Int = 6

A macro could verify that the default is a certain constant expression, presumably.

OTHER TIPS

no... you can't use a default parameter. Also your x(1) should be x.x(1), since the x you're trying to call is a method x on the parameter also called x.

You might want to instead do something like:

def test(x: { def foo(a:Int,b:Option[Int]):Int }) = x.foo(1, b.getOrElse(5))

Or specify a trait defining the method with default args, and mix it into values you want to pass to this method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top