SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 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