Hacker News new | ask | show | jobs
by ankhmoop 6281 days ago
One way to do this in Scala:

  def print[T] (value:T) = System.out.println(value)
  1.until(10).foreach(x => print x)
This is a fairly uninteresting example, however. Something more interesting would be, for instance, the use of structural types to implement type-checked duck typing.

Scala example:

  // Declare a structural type for any class implementing close()
  type Closable = {def close(): Any}
  
  // Executes the provided function with the given
  // closable generator, creating a new instance which
  // will then be closed on completion. The provided
  // function's value will be returned.
  def withClosable[T, C <: Closable] (c: => C) (f: (C) => T) = {
    val closable = c
    try {
      f(closable)
    } finally {
      closable.close
    }
  }
  
  // Example usage
  def usage = {
    val updated = withClosable(db.openConnection) { conn =>
      conn.update("INSERT INTO example VALUES (...")
    }
    System.out.println("Rows updated: " + updated)
  }
This could be compared with Python's new 'with' syntax.