Implicit default value of VS parameter

There are at least two methods in Scala to pass a default value to a method

1) default parameter value

scala> def f(i: Int = 0) = i
f: (i: Int)Int

scala> f()
res0: Int = 0

scala> f(1)
res1: Int = 1

2) implicit parameter

scala> def g(implicit i: Int) = i
g: (implicit i: Int)Int

scala> implicit val default = 0
default: Int = 0

scala> g(1)
res5: Int = 1

scala> g
res7: Int = 0

In which case do you choose one or the other? With the power of implicit defaults, are they useful?

+4
source share
3 answers

You must be sure to select the default setting.

  • You should never create or use implicit parameters of generic types, such as Intor String. See Quote below.
  • The default value is the simplest solution. In terms of the complexity of language features.
  • - "" . , .
  • .
  • .

. : Scala 21.5 / :

.

+10

, , .

, , , :

  • ;
  • .

, , - implicits Scala, ?

implicits " ".

.

, , , , .

, , .

+8

, . , . , ​​:

 def listen(host:String, port:Int = 26000){ ...}

, , 26000, . implicits :

//imagine this is defined in a library 
def listen(host:String, implicit port: Int ) { .. }  

//this is your code which uses that library 
implicit val port = 410000
...
listen("localhost")   //will use 41000

:

implicit val port = 15000
listen("localhost")   //will use 150000

, , , .

:

def f(implicit i: Int = 260000)

, , - 26000, .

+1

Source: https://habr.com/ru/post/1524695/


All Articles