SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Helping Java + Scala Interact




      Implicits, “Pimp My Library” and various conversion helper tools
      simplify the work of interacting with Java.
      Scala and Java have their own completely different collection
      libraries.
      Some builtins ship with Scala to make this easier.




 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   1/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Helping Java + Scala Interact




      Implicits, “Pimp My Library” and various conversion helper tools
      simplify the work of interacting with Java.
      Scala and Java have their own completely different collection
      libraries.
      Some builtins ship with Scala to make this easier.




 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   1/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Helping Java + Scala Interact




      Implicits, “Pimp My Library” and various conversion helper tools
      simplify the work of interacting with Java.
      Scala and Java have their own completely different collection
      libraries.
      Some builtins ship with Scala to make this easier.




 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   1/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Interoperability in Scala 2.7.x



      Scala 2.7.x shipped with scala.collection.jcl.
      scala.collection.jcl.Conversions contained some
      implicit converters, but only to and from the wrapper versions - no
      support for “real” Scala collections.
      Neglected useful base interfaces like Iterator and Iterable
      @jorgeortiz85 provided scala-javautils, which used “Pimp
      My Library” to do a better job.




 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   2/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Interoperability in Scala 2.7.x



      Scala 2.7.x shipped with scala.collection.jcl.
      scala.collection.jcl.Conversions contained some
      implicit converters, but only to and from the wrapper versions - no
      support for “real” Scala collections.
      Neglected useful base interfaces like Iterator and Iterable
      @jorgeortiz85 provided scala-javautils, which used “Pimp
      My Library” to do a better job.




 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   2/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Interoperability in Scala 2.7.x



      Scala 2.7.x shipped with scala.collection.jcl.
      scala.collection.jcl.Conversions contained some
      implicit converters, but only to and from the wrapper versions - no
      support for “real” Scala collections.
      Neglected useful base interfaces like Iterator and Iterable
      @jorgeortiz85 provided scala-javautils, which used “Pimp
      My Library” to do a better job.




 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   2/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Interoperability in Scala 2.8.x
      Scala 2.8.x improves the interop game significantly.
      JCL is gone - focus has shifted to proper interoperability w/ built-in
      types.
      scala.collection.jcl.Conversions replaced by
      scala.collection.JavaConversions - provides implicit
      conversions to & from Scala & Java Collections.
      Includes support for the things missing in 2.7 (Iterable,
      Iterator, etc.)
      Great for places where the compiler can guess what you want
      (implicits); falls short in some cases (like BSON Encoding, as we
      found in Casbah)
      @jorgeortiz85 has updated scala-javautils for 2.8 with
      scalaj-collection
      Explicit asJava / asScala methods for conversions. Adds
      foreach method to Java collections.
 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   3/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Interoperability in Scala 2.8.x
      Scala 2.8.x improves the interop game significantly.
      JCL is gone - focus has shifted to proper interoperability w/ built-in
      types.
      scala.collection.jcl.Conversions replaced by
      scala.collection.JavaConversions - provides implicit
      conversions to & from Scala & Java Collections.
      Includes support for the things missing in 2.7 (Iterable,
      Iterator, etc.)
      Great for places where the compiler can guess what you want
      (implicits); falls short in some cases (like BSON Encoding, as we
      found in Casbah)
      @jorgeortiz85 has updated scala-javautils for 2.8 with
      scalaj-collection
      Explicit asJava / asScala methods for conversions. Adds
      foreach method to Java collections.
 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   3/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Interoperability in Scala 2.8.x
      Scala 2.8.x improves the interop game significantly.
      JCL is gone - focus has shifted to proper interoperability w/ built-in
      types.
      scala.collection.jcl.Conversions replaced by
      scala.collection.JavaConversions - provides implicit
      conversions to & from Scala & Java Collections.
      Includes support for the things missing in 2.7 (Iterable,
      Iterator, etc.)
      Great for places where the compiler can guess what you want
      (implicits); falls short in some cases (like BSON Encoding, as we
      found in Casbah)
      @jorgeortiz85 has updated scala-javautils for 2.8 with
      scalaj-collection
      Explicit asJava / asScala methods for conversions. Adds
      foreach method to Java collections.
 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   3/6
Interlude: Helping Scala + Java play nice together.   Java <-> Scala Basics


Interoperability in Scala 2.8.x
      Scala 2.8.x improves the interop game significantly.
      JCL is gone - focus has shifted to proper interoperability w/ built-in
      types.
      scala.collection.jcl.Conversions replaced by
      scala.collection.JavaConversions - provides implicit
      conversions to & from Scala & Java Collections.
      Includes support for the things missing in 2.7 (Iterable,
      Iterator, etc.)
      Great for places where the compiler can guess what you want
      (implicits); falls short in some cases (like BSON Encoding, as we
      found in Casbah)
      @jorgeortiz85 has updated scala-javautils for 2.8 with
      scalaj-collection
      Explicit asJava / asScala methods for conversions. Adds
      foreach method to Java collections.
 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB             NY Scala Enthusiasts - 8/8/10   3/6
Interlude: Helping Scala + Java play nice together.   Implicits and Pimp Hats


So WTF is an ‘Implicit’, anyway?
      Implicit Arguments
             ‘Explicit’ arguments indicates a method argument you pass, well
             explicitly.
             ‘Implicit’ indicates a method argument which is. . . implied. (But you
             can pass them explicitly too.)
             Implicit arguments are passed in Scala as an additional argument
             list:
                  import com.mongodb._
                  import org.bson.types.ObjectId

                  def query(id: ObjectId)(implicit coll: DBCollection) = coll.findOne(id)

                  val conn = new Mongo()
                  val db = conn.getDB("test")
                  implicit val coll = db.getCollection("testData")

                  // coll is passed implicitly
                  query(new ObjectId())

                  // or we can override the argument
                  query(new ObjectId())(db.getCollection("testDataExplicit"))


             How does this differ from default arguments?
 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB               NY Scala Enthusiasts - 8/8/10   4/6
Interlude: Helping Scala + Java play nice together.   Implicits and Pimp Hats


So WTF is an ‘Implicit’, anyway?
      Implicit Arguments
             ‘Explicit’ arguments indicates a method argument you pass, well
             explicitly.
             ‘Implicit’ indicates a method argument which is. . . implied. (But you
             can pass them explicitly too.)
             Implicit arguments are passed in Scala as an additional argument
             list:
                  import com.mongodb._
                  import org.bson.types.ObjectId

                  def query(id: ObjectId)(implicit coll: DBCollection) = coll.findOne(id)

                  val conn = new Mongo()
                  val db = conn.getDB("test")
                  implicit val coll = db.getCollection("testData")

                  // coll is passed implicitly
                  query(new ObjectId())

                  // or we can override the argument
                  query(new ObjectId())(db.getCollection("testDataExplicit"))


             How does this differ from default arguments?
 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB               NY Scala Enthusiasts - 8/8/10   4/6
Interlude: Helping Scala + Java play nice together.   Implicits and Pimp Hats


So WTF is an ‘Implicit’, anyway?

      Implicit Methods/Conversions
             If you try passing a type to a Scala method argument which doesn’t
             match. . .
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212") // won’t compile


             A fast and loose example, but simple. Fails to compile.
             But with implicit methods, we can provide a conversion path. . .
                  implicit def strToNum(x: String) = x.toInt
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212")


             In a dynamic language, this may be called “monkey patching”.
             Unlike Perl, Python, etc. Scala resolves implicits at compile time.

 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB               NY Scala Enthusiasts - 8/8/10   5/6
Interlude: Helping Scala + Java play nice together.   Implicits and Pimp Hats


So WTF is an ‘Implicit’, anyway?

      Implicit Methods/Conversions
             If you try passing a type to a Scala method argument which doesn’t
             match. . .
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212") // won’t compile


             A fast and loose example, but simple. Fails to compile.
             But with implicit methods, we can provide a conversion path. . .
                  implicit def strToNum(x: String) = x.toInt
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212")


             In a dynamic language, this may be called “monkey patching”.
             Unlike Perl, Python, etc. Scala resolves implicits at compile time.

 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB               NY Scala Enthusiasts - 8/8/10   5/6
Interlude: Helping Scala + Java play nice together.   Implicits and Pimp Hats


So WTF is an ‘Implicit’, anyway?

      Implicit Methods/Conversions
             If you try passing a type to a Scala method argument which doesn’t
             match. . .
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212") // won’t compile


             A fast and loose example, but simple. Fails to compile.
             But with implicit methods, we can provide a conversion path. . .
                  implicit def strToNum(x: String) = x.toInt
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212")


             In a dynamic language, this may be called “monkey patching”.
             Unlike Perl, Python, etc. Scala resolves implicits at compile time.

 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB               NY Scala Enthusiasts - 8/8/10   5/6
Interlude: Helping Scala + Java play nice together.   Implicits and Pimp Hats


So WTF is an ‘Implicit’, anyway?

      Implicit Methods/Conversions
             If you try passing a type to a Scala method argument which doesn’t
             match. . .
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212") // won’t compile


             A fast and loose example, but simple. Fails to compile.
             But with implicit methods, we can provide a conversion path. . .
                  implicit def strToNum(x: String) = x.toInt
                  def printNumber(x: Int) = println(x)

                  printNumber(5)
                  printNumber("212")


             In a dynamic language, this may be called “monkey patching”.
             Unlike Perl, Python, etc. Scala resolves implicits at compile time.

 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB               NY Scala Enthusiasts - 8/8/10   5/6
Interlude: Helping Scala + Java play nice together.    Implicits and Pimp Hats


Pimp My Library
      Coined by Martin Odersky in a 2006 Blog post. Similar to C# extension methods, Ruby modules.

      Uses implicit conversions to tack on new methods at runtime.
      Either return a new “Rich_” or anonymous class. . .

          import com.mongodb.gridfs.{GridFSInputFile => MongoGridFSInputFile}

          class GridFSInputFile protected[mongodb](override val underlying:
                MongoGridFSInputFile) extends GridFSFile {
            def filename_=(name: String) = underlying.setFilename(name)
            def contentType_=(cT: String) = underlying.setContentType(cT)
          }

          object PimpMyMongo {
            implicit def mongoConnAsScala(conn: Mongo) = new {
              def asScala = new MongoConnection(conn)
            }

              implicit def enrichGridFSInput(in: MongoGridFSInputFile) =
                new GridFSInputFile(in)
          }

          import PimpMyMongo._



      A note: with regards to type boundaries, [A <:    SomeType] won’t allow implicitly converted values. You can whitelist

      them by using [A <% SomeType] instead.

 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB                NY Scala Enthusiasts - 8/8/10    6/6
Interlude: Helping Scala + Java play nice together.    Implicits and Pimp Hats


Pimp My Library
      Coined by Martin Odersky in a 2006 Blog post. Similar to C# extension methods, Ruby modules.

      Uses implicit conversions to tack on new methods at runtime.
      Either return a new “Rich_” or anonymous class. . .

          import com.mongodb.gridfs.{GridFSInputFile => MongoGridFSInputFile}

          class GridFSInputFile protected[mongodb](override val underlying:
                MongoGridFSInputFile) extends GridFSFile {
            def filename_=(name: String) = underlying.setFilename(name)
            def contentType_=(cT: String) = underlying.setContentType(cT)
          }

          object PimpMyMongo {
            implicit def mongoConnAsScala(conn: Mongo) = new {
              def asScala = new MongoConnection(conn)
            }

              implicit def enrichGridFSInput(in: MongoGridFSInputFile) =
                new GridFSInputFile(in)
          }

          import PimpMyMongo._



      A note: with regards to type boundaries, [A <:    SomeType] won’t allow implicitly converted values. You can whitelist

      them by using [A <% SomeType] instead.

 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB                NY Scala Enthusiasts - 8/8/10    6/6
Interlude: Helping Scala + Java play nice together.    Implicits and Pimp Hats


Pimp My Library
      Coined by Martin Odersky in a 2006 Blog post. Similar to C# extension methods, Ruby modules.

      Uses implicit conversions to tack on new methods at runtime.
      Either return a new “Rich_” or anonymous class. . .

          import com.mongodb.gridfs.{GridFSInputFile => MongoGridFSInputFile}

          class GridFSInputFile protected[mongodb](override val underlying:
                MongoGridFSInputFile) extends GridFSFile {
            def filename_=(name: String) = underlying.setFilename(name)
            def contentType_=(cT: String) = underlying.setContentType(cT)
          }

          object PimpMyMongo {
            implicit def mongoConnAsScala(conn: Mongo) = new {
              def asScala = new MongoConnection(conn)
            }

              implicit def enrichGridFSInput(in: MongoGridFSInputFile) =
                new GridFSInputFile(in)
          }

          import PimpMyMongo._



      A note: with regards to type boundaries, [A <:    SomeType] won’t allow implicitly converted values. You can whitelist

      them by using [A <% SomeType] instead.

 B.W. McAdams (Novus Partners)                 Integrating Scala + MongoDB                NY Scala Enthusiasts - 8/8/10    6/6

Más contenido relacionado

La actualidad más candente

Easy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolEasy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolHasitha Guruge
 
Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Knoldus Inc.
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021Thodoris Bais
 
Leveraging your Knowledge of ORM Towards Performance-based NoSQL Technology
Leveraging your Knowledge of ORM Towards Performance-based NoSQL TechnologyLeveraging your Knowledge of ORM Towards Performance-based NoSQL Technology
Leveraging your Knowledge of ORM Towards Performance-based NoSQL TechnologyDATAVERSITY
 
Writing Efficient Java Applications For My Sql Cluster Using Ndbj
Writing Efficient Java Applications For My Sql Cluster Using NdbjWriting Efficient Java Applications For My Sql Cluster Using Ndbj
Writing Efficient Java Applications For My Sql Cluster Using NdbjMySQLConference
 
JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the CloudStephen Chin
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopSvetlin Nakov
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBXESUG
 
Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)Trisha Gee
 

La actualidad más candente (20)

Jndi (1)
Jndi (1)Jndi (1)
Jndi (1)
 
Easy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping ToolEasy Data Object Relational Mapping Tool
Easy Data Object Relational Mapping Tool
 
Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2
 
Oak Lucene Indexes
Oak Lucene IndexesOak Lucene Indexes
Oak Lucene Indexes
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
 
Leveraging your Knowledge of ORM Towards Performance-based NoSQL Technology
Leveraging your Knowledge of ORM Towards Performance-based NoSQL TechnologyLeveraging your Knowledge of ORM Towards Performance-based NoSQL Technology
Leveraging your Knowledge of ORM Towards Performance-based NoSQL Technology
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Orcale Presentation
Orcale PresentationOrcale Presentation
Orcale Presentation
 
Writing Efficient Java Applications For My Sql Cluster Using Ndbj
Writing Efficient Java Applications For My Sql Cluster Using NdbjWriting Efficient Java Applications For My Sql Cluster Using Ndbj
Writing Efficient Java Applications For My Sql Cluster Using Ndbj
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 
Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5
 
Hadoop 101
Hadoop 101Hadoop 101
Hadoop 101
 
JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the Cloud
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache Hadoop
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBX
 
Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)Java 8 in Anger (QCon London)
Java 8 in Anger (QCon London)
 
MongoDB Webtech conference 2010
MongoDB Webtech conference 2010MongoDB Webtech conference 2010
MongoDB Webtech conference 2010
 

Similar a Briefly: Scala Implicits, Pimp My Library and Java Interop

Scala for n00bs by a n00b.
Scala for n00bs by a n00b.Scala for n00bs by a n00b.
Scala for n00bs by a n00b.brandongulla
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaDerek Chen-Becker
 
Scala overview
Scala overviewScala overview
Scala overviewSteve Min
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuHavoc Pennington
 
5分で説明する Play! scala
5分で説明する Play! scala5分で説明する Play! scala
5分で説明する Play! scalamasahitojp
 
Lessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its EcosystemLessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its EcosystemPetr Hošek
 
5 Takeaways from Migrating a Library to Scala 3 - Scala Love
5 Takeaways from Migrating a Library to Scala 3 - Scala Love5 Takeaways from Migrating a Library to Scala 3 - Scala Love
5 Takeaways from Migrating a Library to Scala 3 - Scala LoveNatan Silnitsky
 
Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaManjula Kollipara
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Futuremircodotta
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapDave Orme
 
Beginning scala 02 15
Beginning scala 02 15Beginning scala 02 15
Beginning scala 02 15lancegatlin
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and HowBigBlueHat
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to ScalaBrent Lemons
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterpriseRafael Bagmanov
 

Similar a Briefly: Scala Implicits, Pimp My Library and Java Interop (20)

Scala for n00bs by a n00b.
Scala for n00bs by a n00b.Scala for n00bs by a n00b.
Scala for n00bs by a n00b.
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Sbt
SbtSbt
Sbt
 
Scala overview
Scala overviewScala overview
Scala overview
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 
5分で説明する Play! scala
5分で説明する Play! scala5分で説明する Play! scala
5分で説明する Play! scala
 
SBT Crash Course
SBT Crash CourseSBT Crash Course
SBT Crash Course
 
Lessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its EcosystemLessons Learned: Scala and its Ecosystem
Lessons Learned: Scala and its Ecosystem
 
5 Takeaways from Migrating a Library to Scala 3 - Scala Love
5 Takeaways from Migrating a Library to Scala 3 - Scala Love5 Takeaways from Migrating a Library to Scala 3 - Scala Love
5 Takeaways from Migrating a Library to Scala 3 - Scala Love
 
Devoxx
DevoxxDevoxx
Devoxx
 
Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kollipara
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Future
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
Beginning scala 02 15
Beginning scala 02 15Beginning scala 02 15
Beginning scala 02 15
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
All about scala
All about scalaAll about scala
All about scala
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterprise
 

Último

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Último (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

Briefly: Scala Implicits, Pimp My Library and Java Interop

  • 1. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Helping Java + Scala Interact Implicits, “Pimp My Library” and various conversion helper tools simplify the work of interacting with Java. Scala and Java have their own completely different collection libraries. Some builtins ship with Scala to make this easier. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 1/6
  • 2. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Helping Java + Scala Interact Implicits, “Pimp My Library” and various conversion helper tools simplify the work of interacting with Java. Scala and Java have their own completely different collection libraries. Some builtins ship with Scala to make this easier. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 1/6
  • 3. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Helping Java + Scala Interact Implicits, “Pimp My Library” and various conversion helper tools simplify the work of interacting with Java. Scala and Java have their own completely different collection libraries. Some builtins ship with Scala to make this easier. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 1/6
  • 4. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Interoperability in Scala 2.7.x Scala 2.7.x shipped with scala.collection.jcl. scala.collection.jcl.Conversions contained some implicit converters, but only to and from the wrapper versions - no support for “real” Scala collections. Neglected useful base interfaces like Iterator and Iterable @jorgeortiz85 provided scala-javautils, which used “Pimp My Library” to do a better job. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 2/6
  • 5. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Interoperability in Scala 2.7.x Scala 2.7.x shipped with scala.collection.jcl. scala.collection.jcl.Conversions contained some implicit converters, but only to and from the wrapper versions - no support for “real” Scala collections. Neglected useful base interfaces like Iterator and Iterable @jorgeortiz85 provided scala-javautils, which used “Pimp My Library” to do a better job. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 2/6
  • 6. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Interoperability in Scala 2.7.x Scala 2.7.x shipped with scala.collection.jcl. scala.collection.jcl.Conversions contained some implicit converters, but only to and from the wrapper versions - no support for “real” Scala collections. Neglected useful base interfaces like Iterator and Iterable @jorgeortiz85 provided scala-javautils, which used “Pimp My Library” to do a better job. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 2/6
  • 7. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Interoperability in Scala 2.8.x Scala 2.8.x improves the interop game significantly. JCL is gone - focus has shifted to proper interoperability w/ built-in types. scala.collection.jcl.Conversions replaced by scala.collection.JavaConversions - provides implicit conversions to & from Scala & Java Collections. Includes support for the things missing in 2.7 (Iterable, Iterator, etc.) Great for places where the compiler can guess what you want (implicits); falls short in some cases (like BSON Encoding, as we found in Casbah) @jorgeortiz85 has updated scala-javautils for 2.8 with scalaj-collection Explicit asJava / asScala methods for conversions. Adds foreach method to Java collections. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 3/6
  • 8. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Interoperability in Scala 2.8.x Scala 2.8.x improves the interop game significantly. JCL is gone - focus has shifted to proper interoperability w/ built-in types. scala.collection.jcl.Conversions replaced by scala.collection.JavaConversions - provides implicit conversions to & from Scala & Java Collections. Includes support for the things missing in 2.7 (Iterable, Iterator, etc.) Great for places where the compiler can guess what you want (implicits); falls short in some cases (like BSON Encoding, as we found in Casbah) @jorgeortiz85 has updated scala-javautils for 2.8 with scalaj-collection Explicit asJava / asScala methods for conversions. Adds foreach method to Java collections. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 3/6
  • 9. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Interoperability in Scala 2.8.x Scala 2.8.x improves the interop game significantly. JCL is gone - focus has shifted to proper interoperability w/ built-in types. scala.collection.jcl.Conversions replaced by scala.collection.JavaConversions - provides implicit conversions to & from Scala & Java Collections. Includes support for the things missing in 2.7 (Iterable, Iterator, etc.) Great for places where the compiler can guess what you want (implicits); falls short in some cases (like BSON Encoding, as we found in Casbah) @jorgeortiz85 has updated scala-javautils for 2.8 with scalaj-collection Explicit asJava / asScala methods for conversions. Adds foreach method to Java collections. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 3/6
  • 10. Interlude: Helping Scala + Java play nice together. Java <-> Scala Basics Interoperability in Scala 2.8.x Scala 2.8.x improves the interop game significantly. JCL is gone - focus has shifted to proper interoperability w/ built-in types. scala.collection.jcl.Conversions replaced by scala.collection.JavaConversions - provides implicit conversions to & from Scala & Java Collections. Includes support for the things missing in 2.7 (Iterable, Iterator, etc.) Great for places where the compiler can guess what you want (implicits); falls short in some cases (like BSON Encoding, as we found in Casbah) @jorgeortiz85 has updated scala-javautils for 2.8 with scalaj-collection Explicit asJava / asScala methods for conversions. Adds foreach method to Java collections. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 3/6
  • 11. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats So WTF is an ‘Implicit’, anyway? Implicit Arguments ‘Explicit’ arguments indicates a method argument you pass, well explicitly. ‘Implicit’ indicates a method argument which is. . . implied. (But you can pass them explicitly too.) Implicit arguments are passed in Scala as an additional argument list: import com.mongodb._ import org.bson.types.ObjectId def query(id: ObjectId)(implicit coll: DBCollection) = coll.findOne(id) val conn = new Mongo() val db = conn.getDB("test") implicit val coll = db.getCollection("testData") // coll is passed implicitly query(new ObjectId()) // or we can override the argument query(new ObjectId())(db.getCollection("testDataExplicit")) How does this differ from default arguments? B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 4/6
  • 12. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats So WTF is an ‘Implicit’, anyway? Implicit Arguments ‘Explicit’ arguments indicates a method argument you pass, well explicitly. ‘Implicit’ indicates a method argument which is. . . implied. (But you can pass them explicitly too.) Implicit arguments are passed in Scala as an additional argument list: import com.mongodb._ import org.bson.types.ObjectId def query(id: ObjectId)(implicit coll: DBCollection) = coll.findOne(id) val conn = new Mongo() val db = conn.getDB("test") implicit val coll = db.getCollection("testData") // coll is passed implicitly query(new ObjectId()) // or we can override the argument query(new ObjectId())(db.getCollection("testDataExplicit")) How does this differ from default arguments? B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 4/6
  • 13. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats So WTF is an ‘Implicit’, anyway? Implicit Methods/Conversions If you try passing a type to a Scala method argument which doesn’t match. . . def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") // won’t compile A fast and loose example, but simple. Fails to compile. But with implicit methods, we can provide a conversion path. . . implicit def strToNum(x: String) = x.toInt def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") In a dynamic language, this may be called “monkey patching”. Unlike Perl, Python, etc. Scala resolves implicits at compile time. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 5/6
  • 14. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats So WTF is an ‘Implicit’, anyway? Implicit Methods/Conversions If you try passing a type to a Scala method argument which doesn’t match. . . def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") // won’t compile A fast and loose example, but simple. Fails to compile. But with implicit methods, we can provide a conversion path. . . implicit def strToNum(x: String) = x.toInt def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") In a dynamic language, this may be called “monkey patching”. Unlike Perl, Python, etc. Scala resolves implicits at compile time. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 5/6
  • 15. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats So WTF is an ‘Implicit’, anyway? Implicit Methods/Conversions If you try passing a type to a Scala method argument which doesn’t match. . . def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") // won’t compile A fast and loose example, but simple. Fails to compile. But with implicit methods, we can provide a conversion path. . . implicit def strToNum(x: String) = x.toInt def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") In a dynamic language, this may be called “monkey patching”. Unlike Perl, Python, etc. Scala resolves implicits at compile time. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 5/6
  • 16. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats So WTF is an ‘Implicit’, anyway? Implicit Methods/Conversions If you try passing a type to a Scala method argument which doesn’t match. . . def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") // won’t compile A fast and loose example, but simple. Fails to compile. But with implicit methods, we can provide a conversion path. . . implicit def strToNum(x: String) = x.toInt def printNumber(x: Int) = println(x) printNumber(5) printNumber("212") In a dynamic language, this may be called “monkey patching”. Unlike Perl, Python, etc. Scala resolves implicits at compile time. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 5/6
  • 17. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats Pimp My Library Coined by Martin Odersky in a 2006 Blog post. Similar to C# extension methods, Ruby modules. Uses implicit conversions to tack on new methods at runtime. Either return a new “Rich_” or anonymous class. . . import com.mongodb.gridfs.{GridFSInputFile => MongoGridFSInputFile} class GridFSInputFile protected[mongodb](override val underlying: MongoGridFSInputFile) extends GridFSFile { def filename_=(name: String) = underlying.setFilename(name) def contentType_=(cT: String) = underlying.setContentType(cT) } object PimpMyMongo { implicit def mongoConnAsScala(conn: Mongo) = new { def asScala = new MongoConnection(conn) } implicit def enrichGridFSInput(in: MongoGridFSInputFile) = new GridFSInputFile(in) } import PimpMyMongo._ A note: with regards to type boundaries, [A <: SomeType] won’t allow implicitly converted values. You can whitelist them by using [A <% SomeType] instead. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 6/6
  • 18. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats Pimp My Library Coined by Martin Odersky in a 2006 Blog post. Similar to C# extension methods, Ruby modules. Uses implicit conversions to tack on new methods at runtime. Either return a new “Rich_” or anonymous class. . . import com.mongodb.gridfs.{GridFSInputFile => MongoGridFSInputFile} class GridFSInputFile protected[mongodb](override val underlying: MongoGridFSInputFile) extends GridFSFile { def filename_=(name: String) = underlying.setFilename(name) def contentType_=(cT: String) = underlying.setContentType(cT) } object PimpMyMongo { implicit def mongoConnAsScala(conn: Mongo) = new { def asScala = new MongoConnection(conn) } implicit def enrichGridFSInput(in: MongoGridFSInputFile) = new GridFSInputFile(in) } import PimpMyMongo._ A note: with regards to type boundaries, [A <: SomeType] won’t allow implicitly converted values. You can whitelist them by using [A <% SomeType] instead. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 6/6
  • 19. Interlude: Helping Scala + Java play nice together. Implicits and Pimp Hats Pimp My Library Coined by Martin Odersky in a 2006 Blog post. Similar to C# extension methods, Ruby modules. Uses implicit conversions to tack on new methods at runtime. Either return a new “Rich_” or anonymous class. . . import com.mongodb.gridfs.{GridFSInputFile => MongoGridFSInputFile} class GridFSInputFile protected[mongodb](override val underlying: MongoGridFSInputFile) extends GridFSFile { def filename_=(name: String) = underlying.setFilename(name) def contentType_=(cT: String) = underlying.setContentType(cT) } object PimpMyMongo { implicit def mongoConnAsScala(conn: Mongo) = new { def asScala = new MongoConnection(conn) } implicit def enrichGridFSInput(in: MongoGridFSInputFile) = new GridFSInputFile(in) } import PimpMyMongo._ A note: with regards to type boundaries, [A <: SomeType] won’t allow implicitly converted values. You can whitelist them by using [A <% SomeType] instead. B.W. McAdams (Novus Partners) Integrating Scala + MongoDB NY Scala Enthusiasts - 8/8/10 6/6