Created
January 7, 2012 16:50
-
-
Save langley/1575292 to your computer and use it in GitHub Desktop.
Simple Example of Using a Scala Implicit with sbt and the REPL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This gist shows a VERY simple use of Scala implicits and how to use it from | |
sbt & the scala console. | |
Create these two files... | |
============================================================================= | |
Xp.scala | |
----------------------------------------------------------------------------- | |
package xp { | |
class Xp { | |
def beep() = { println("beep!") } | |
} | |
object Xp { | |
implicit def string2Xp(s: String) : Xp = { new Xp } | |
} | |
} | |
============================================================================= | |
Yp.scala | |
-----------------------------------------------------------------------------] | |
package xp { | |
object Yp { | |
import xp.Xp._ | |
def apply(): Unit = { "a".beep } | |
} | |
} | |
============================================================================= | |
Now, in your console at the command line... | |
langley@home:$ ls | |
Xp.scala Yp.scala | |
langley@home:$ sbt | |
[info] Set current project to default-f28379 (in build file:/local/home/langley/lab/hacking/xplicits/) | |
> compile | |
[info] Updating {file:/local/home/langley/lab/hacking/xplicits/}default-f28379... | |
[info] Resolving org.scala-lang#scala-library;2.9.1 ... | |
[info] Done updating. | |
[info] Compiling 2 Scala sources to /local/home/langley/lab/hacking/xplicits/target/scala-2.9.1/classes... | |
[success] Total time: 5 s, completed Jan 7, 2012 11:48:52 AM | |
> console | |
[info] Starting scala interpreter... | |
[info] | |
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_21). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> val y = xp.Yp | |
y: xp.Yp.type = xp.Yp$@71d9a2ab | |
scala> y() | |
beep! | |
scala> | |
[success] Total time: 59 s, completed Jan 7, 2012 11:49:54 AM | |
> langley@home:$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment