Implicit Type Conversion in Scala

package com.vff.lessons

import java.io.File
import java.io.FileInputStream
import javax.swing.JOptionPane

/**
 * This class demonstrates how to make implicitly convert one type T to another U
 * allowing methods taking parameter T also take parameter U
 */
object ImplicitConversion extends App {

  // Automatically allow File arguments to be passed as Strings.
  implicit def stringToFile(name:String): File = new File(name)

  // cheap and cheerful / not-very functional file reading. Lol.
  def readFile(file:File) = {
    val fs = new FileInputStream(file)
    val buffer = new Array[Byte](fs.available)
    fs.read(buffer)
    fs.close()
    println(new String(buffer))
  }
  
  // Pop-up a dialog asking for the filename.
  val name = JOptionPane.showInputDialog("Filename?")
  
  // readFile(File) now takes our String.
  println(readFile(name))
  
}

Implicit type-conversion is very powerful but the implicit keyword is alien to a lot of non-scala developers.

Advertisements

One thought on “Implicit Type Conversion in Scala

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s