Unexpected behavior when implicit method arguments also support default values?

57 views
Skip to first unread message

Dean Wampler

unread,
Jul 9, 2014, 1:09:02 PM7/9/14
to scala-user
Welcome to Scala version 2.11.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
...
scala> def m(implicit i:Int = 0) = println(i)
m: (implicit i: Int)Unit

scala> m()
0

scala> m
0

scala> implicit val iv = 10
iv: Int = 10

scala> m
10

scala> m()
0


This sort of breaks the "principle of least surprise".

--
Dean Wampler, Ph.D.

Bob Hiestand

unread,
Jul 9, 2014, 1:23:50 PM7/9/14
to Dean Wampler, scala-user
Speaking only for myself, it doesn't seem surprising.  m is defined as not having an argument list, with an implicit list.  Therefore 'm' means "apply an implicit", but 'm()' means "I'm passing the (lack of) implicit parameter explicitly".

bob




--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jason Zaugg

unread,
Jul 9, 2014, 1:24:16 PM7/9/14
to Dean Wampler, scala-user
On Wednesday, July 9, 2014, Dean Wampler <deanw...@gmail.com> wrote:
Welcome to Scala version 2.11.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
...
scala> def m(implicit i:Int = 0) = println(i)
m: (implicit i: Int)Unit

scala> m()
0

scala> m
0

scala> implicit val iv = 10
iv: Int = 10

scala> m
10

scala> m()
0


This sort of breaks the "principle of least surprise".

Arguably it is in poor style to define implicit params with defaults, but the results aren't that surprising IMO. The implicit argument list is only provided by the compiler if you don't provide it explicitly. Your second example does provide it explicitly, albeit short argument, which is where defaults are triggered. 

Jason 

Simon Ochsenreither

unread,
Jul 9, 2014, 8:48:06 PM7/9/14
to scala...@googlegroups.com, deanw...@gmail.com
Would it be reasonable to allow mixing default parameters and implicits?

Not sure if there are real world use cases out there which depend on that ...

Sonnenschein

unread,
Jul 10, 2014, 8:15:18 AM7/10/14
to scala...@googlegroups.com, deanw...@gmail.com
Simon: Sure there are...
Reply all
Reply to author
Forward
0 new messages