alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (spec-funs.scala)

This example Scala source code file (spec-funs.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

absfunction1, absfunction1, array, array, closuretest, int, int, inttest, t, testclosure, testint, u, u

The Scala spec-funs.scala source code

trait AbsFunction1[@specialized -T, @specialized +U] {
  def apply(x: T): U
}

final class IntTest {

  val niters = 10000

  def transF(xs: Array[Int], f: AbsFunction1[Int, Int]) = {
    var i = 0
    var s = 0
    while (i < xs.length) {
      xs(i) = f(xs(i)) + 1
      i += 1
    }
  }

  def run() {
    val xs = new Array[Int](10000)
    val f = new AbsFunction1[Int, Int] {
      def apply(x: Int): Int = x * x
    }    
    for (j <- 0 until niters) {
      transF(xs, f)
    }
    var acc = 0
    for (i <- 0 until xs.length) acc += xs(i)
    println(acc)
  }
}

final class ClosureTest {

  val niters = 10000

  def transF(xs: Array[Int], f: Int => Int) = {
    var i = 0
    var s = 0
    while (i < xs.length) {
      xs(i) = f.apply(xs(i)) + 1
      i += 1
    }
  }

  def run() {
    val xs = new Array[Int](10000)
//    val f = (x: Int) => x * x
    for (j <- 0 until niters) {
      transF(xs, x => x * x)
    }
    var acc = 0
    for (i <- 0 until xs.length) acc += xs(i)
    println(acc)
  }
}

object TestInt extends testing.Benchmark {
  def run() = (new IntTest).run()
}

object TestClosure extends testing.Benchmark {
  def run() = (new ClosureTest).run()
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala spec-funs.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.