10 ms·
Scala: Understanding implicits
- namuol 8y ago(Would be helpful to include "Scala" somewhere in the title)
- alexanderdmitri 8y agoThat it's about Scala is implicit in the title :P
- Randgalt 8y agoTouche :D
- justinjlynn 8y agoFor when you've completed that here's an application (with an amusing name): http://eugenezhulenev.com/blog/2017/04/26/type-level-instant-insanity-in-scala/ http://eugenezhulenev.com/blog/2017/04/26/type-level-instant...
- wging 8y agoReminds me of https://aphyr.com/posts/342-typing-the-technical-interview https://aphyr.com/posts/342-typing-the-technical-interview
- justinjlynn 8y agoAs to technical interviews I've always believed the rule was: ask a silly question, get a silly (but still enlightening) answer. That series of blog posts is the height of this precept.
- AheadOfTime295 8y agoRe implicits and their interplay with macros: Achieving 3.2x Faster Scala Compile Time Diagnostics: - A method takes an implicit parameter to be filled in by the compiler - the Scala compiler synthesizes an argument for that parameter using macros - instead of using an existing value in the implicit scope Conclusion: that's why a small source file took so long to typecheck. Details at https://jobs.zalando.com/tech/blog/achieving-3.2x-faster-scala-compile-time/ https://jobs.zalando.com/tech/blog/achieving-3.2x-faster-sca...
- harpocrates 8y agoI heartily recommend [splain][0] to anyone debugging non-trivial implicits. It is a scalac compiler plugin that, among other things, will swap out the horribly unhelpful "implicit not found" or "diverging implicit expansion" messages for an indented and annotated representation of the search tree that the compiler went through before giving up. `-Xlog-implicits` is good to use every now and then, but it quickly becomes unreadable for any decent sized project. [0]: https://github.com/tek/splain
- threeseed 8y agoI can't understand why this is not built into Scala. It is utterly essential if you are doing anything with implicits. In particular with libraries like Circe.
- psynapse 8y agoI wish I knew about this when I wrote Scala (albeit briefly). It's one of those "ill posed problems" when debugging - what is the implicit from a third party library that is not in scope that makes this work?
- bad_user 8y agoWell grown libraries are using the `@implicitNotFound` annotation to generate better library-controlled compiler errors, with advice given for what to do. It has its limitations of course, but proved very useful in many situations. A search tree is cool, but it's not going to explain how to get a value when it has restrictions (dependencies).
- harpocrates 8y ago`@implicitNotFound` still only gives you a top-level failure message. Also, my comment was aimed more at developers of libraries with complex implicit derivations not the consumers of such libraries.
- AheadOfTime295 8y agoIt will be interesting to try out implicits in the upcoming Twitter's Reasonable Scala Compiler [0] According to [1] a working version will be ready before originally planned: > Recently, Stu Hood came up with a groundbreaking idea. He suggested > that Rsc can become useful much earlier that we initially thought. [0] https://github.com/twitter/rsc https://github.com/twitter/rsc [1] https://github.com/twitter/rsc/commit/ebc3019c06c9e175311541637ec31047fb914c4b https://github.com/twitter/rsc/commit/ebc3019c06c9e175311541...
- doikor 8y agoThere is also some interesting work (for dotty only atm) on doing the type checking in two phases which would allow the second phase to be parallelized. This could be paired together with the Rsc type checker for the first pass for even bigger improvements. https://github.com/lampepfl/dotty/pull/4767 https://github.com/lampepfl/dotty/pull/4767
- weego 8y agoThe best summary is why bother when coding explicitly and without "magic" is far more suitable to long term maintainable code
- bad_user 8y agoImplicit parameters in Scala are solved at compile time and lexically scoped so do not qualify for "magic". > why bother Because software development is hard, we're solving hard problems and it's good to have better and better tools to do that. In particular Scala's implicit parameters, along with its support for higher kinded types and functional programming in general allow for modeling your problem domain via tools imported from Haskell and other FP languages, because implicit parameters are in fact a generalization of type classes. And type classes are many times a superior alternative to OOP for building polymorphic code. Plus the landscape is very competitive and the market is global. I remember in 2000 when the bubble burst the jobs of thousands of developers disappeared over night. To stay competitive, a "why bother" attitude is not going to cut it when the current bubble bursts, just saying.
- couchand 8y ago> solved at compile time and lexically scoped so do not qualify for "magic". That seems like too limiting a definition of "magic" to me. > implicit parameters are in fact a generalization of type classes. Well, not exactly, as far as I can tell. Type classes (in Haskell at least) are significantly more ergonomic. Since they semantically describe the user's types, they allow you to perform their operations directly with the user's values. Implicit parameters have to be pulled out of the implicit environment and used explicitly themselves, as far as I can tell. It's true that the underlying mechanism is (roughly) the same, but the surface-level behavior is what really matters, and there they are very different.
- bad_user 8y ago> "That seems like too limiting a definition of "magic" to me" What is your definition of "magic" then? Things that are unfamiliar? Please don't mention "explicit vs implicit", because Scala's implicits are in fact explicit, plus we can always talk of assembly language and how it lacks any magic. > "Well, not exactly, as far as I can tell. Type classes (in Haskell at least) are significantly more ergonomic." Ergonomics has nothing to do with whether a concept is a generalization of another. > "Since they semantically describe the user's types, they allow you to perform their operations directly with the user's values. Implicit parameters have to be pulled out of the implicit environment and used explicitly themselves, as far as I can tell." Nope, both type clases and implicit parameters allow for describing functions that turn type names into values. That's all there is to it. Or in other words, both type classes and Scala's implicits are about return type polymorphism. The only actual differences are that: 1. type classes in Haskell are supposedly coherent, i.e. the compiler is supposed to force a single type class instance in the whole project, however GHC does in fact not do that so you can end up with multiple instances of the same type in the same project 2. Scala's implicits are more flexible in what they allow, for example it has priority rules in case of conflicts, which allow say those implicits to work in the presence of OOP subtyping, or to work with multiple type params for describing things that are difficult to describe via type classes (but not necessarily desirable, e.g. the CanBuildFrom pattern) 3. working with Haskell's type classes is nicer, because for hierarchies in Scala you end up dealing with OOP issues (i.e. in modelling Haskell's type class hierarchies, we ended up debating on inheritance vs composition), plus we do a lot of manual plumbing in libraries like Typelevel Cats But trust me when I say this, fundamentally they are the same ;-) You can also read Martin Odersky's paper about it: http://ropas.snu.ac.kr/%7Ebruno/papers/TypeClasses.pdf http://ropas.snu.ac.kr/%7Ebruno/papers/TypeClasses.pdf
- paulddraper 8y agoI've seen uses of implicits fall into three categories: (1) Dependency injection, e.g. ExecutionContext (2) DSLs/syntax sugar, e.g. custom string interpolation, specs2 (3) Typeclasses and type-level programming, e.g. Play JSON Reads/Writes, cats, shapeless The more I have seen Scala, the more I realize that #1 is cancer. Implicits should not be used to reduce the number of characters typed. If used at all, they should be used for a better reason, e.g. it is a necessary part of a typesafe pattern, like typeclasses.
- bad_user 8y agoImplicits are great. People unfortunately go to great length to avoid typing function parameters so will do all kinds of shit to reduce arguments in function calls. This includes all kinds of insane dependency injection frameworks that depend on runtime introspection or bytecode manipulation, or stateful objects being passed around instead of plain values. There's even this best practice around that says "have functions with 3 params or less" which is complete bullshit. I mean, you actually have company wide policies with enforced lint rules on maximum number of params and people end up passing around giant records (maps, objects) that then get unwrapped. I cannot blame implicits, if anything, if people are going to go to such great lengths to avoid passing arguments in functions, I'd rather see implicits instead of Spring or Guice, because at the very least implicits are compile time. The actual cancer are the best practices that drive people to doing this.
- forkerenok 8y agoI wouldn't say that best practices drive people to doing stupid stuff, at least not directly. And they usually do have merit. The issue is that people apply them without understanding the motivations behind. F.x. the "too many method or constructor args" warning signals that a class or a method is probably doing too much, so please decompose. A person without understanding the motivation will think it's a sort of a game and wrap some params into a map or move some them into globals :-\
- pjmlp 8y ago
- rajman187 8y agoOff topic but annoying (and pedantic on my part) nonetheless, "begging the question" does not mean what the author seems to think.
- peeyek 8y agoScala is like Rust and Rust is like Scala. They are proud of their complexity.
- paulddraper 8y agoIf there's one thing better than a Scala vs Kotlin flamewar or a Rust vs Go flamewar, it's undoubtedly a mashup of the two.
- rcaught 8y agoCan we all just get along and agree that at least none of them are Javascript?
- owl57 8y agoI believe a big part of the famous Javascript semantics can be emulated in Scala with a library. Once upon a time I wrote a toy Android app with Scaloid, and tried to use some on-device print-debugging. toast("foo") worked just fine. toast(42) crashed at runtime. Turns out Scaloid offers an implicit conversion from Int to CharSequence, and it even doesn't turn 42 into anything like "42". I'm not kidding [1]. In Android you normally have "resource identifiers" as integers with no compile-time type information, and then at runtime you never use these as actual numbers, instead you every single time pass them to some function like getText or getDrawable. Sound like the perfect case for implicit conversion, right? [1] https://github.com/pocorall/scaloid/blob/b4fcbd0c25870941af727b382cee500600b7594e/scaloid-common/src/main/scala/org/scaloid/common/implicits.scala#L56 https://github.com/pocorall/scaloid/blob/b4fcbd0c25870941af7...
- masklinn 8y agoI commonly see this assertion but it never made much sense to me: Rust is not that complex, and it's certainly nowhere near the complexity of Scala or C++ let alone worse (to me the sole topic of C++ constructors & assignment feels more complex than the entirety of Rust). What it is is highly front-loaded, especially through the early learning cliff of integrating the borrow checker.
- emodendroket 8y agoIn general I feel like implicits are not a great feature.
- hnbroseph 8y agoi wonder if implicits could present a security risk, insofar as the compiler may grab some [perhaps mistakenly in-scope] identifier which has sensitive data on it.
- joshlemer 8y agoAlso see Martin Odersky's recent talk about abstracting context using implicits https://youtu.be/uiorT754IwA https://youtu.be/uiorT754IwA
- cutler 8y agoIf you keep an eye on Indeed.com and Angel.co you'll notice a decline in Scala adoption over the last few years. I can't help thinking implicits are partly responsible for this. They're certainly the main reason I ditched Scala. More than any other language there seem to be more exmaples, with Scala, of a team trying it then switching to something simpler.
- dionian 8y agopeople write terrible java code, java is fine. no surprise scala suffers from that worse since it has a lot more power
- hderms 8y agoI think implicits are fine as long as they're used primarily for the typeclass pattern. The extension methods and conversions aspect of implicits should be confined to library DSLs