List of multiple parameters and default arguments

Compilation of this code:

class Test {

  def f(arg: Int)(defaultArg: String => Unit = println): Unit = ???

  f(42)
}

not working with

missing argument list for method f in class Test [error] Unapplied methods are only converted to functions when a function type is expected. [error] You can make this conversion explicit by writing `f _` or `f(_)(_)` instead of `f`. [error] f(42) [error] ^ [error] one error found

Why is this failing? Is it ambiguous? Is it possible to make it work without using a list of single parameters?

+4
source share
2 answers

The correct syntax for your case is as follows:

f(42)()

You can call f (42) by specifying defaultArg as implicit:

def f(arg: Int)(implicit defaultArg: String => Unit = println): Unit = ???

Then you can call it:

f(42)
+8
source

, Int , . , f(42), , Int . , . , f(42), . , , .

:

val ptln1:String=>Unit = System.out.println _ //Doing this to show the type of the println function
def f(arg: Int)(defaultArg: String => Unit = ptln1): Unit = ???
val t = f(42)()

, , .
, , implicits, ,

def f(arg: Int)(implicit defaultArg: String => Unit = println _): Unit = ???
f(42)()

,

  def f(arg: Int)(defaultArg: String => Unit = println _): Unit = ???
  val t = f(42)()

, println. , .

implicit def testPrint(str:String):Unit = ???

   def f(arg: Int)(implicit defaultArg: String => Unit = testPrint): Unit = ???

   val t = f(42)

,

   def testPrint(str:String):Unit = ???

   def f(arg: Int)(defaultArg: String => Unit = testPrint): Unit = ???

   val t = f(42)()
0

All Articles