Skip to content

Instantly share code, notes, and snippets.

@davetron5000
Created July 21, 2009 00:20
Show Gist options
  • Save davetron5000/151005 to your computer and use it in GitHub Desktop.
Save davetron5000/151005 to your computer and use it in GitHub Desktop.
// define a class called "Circle"
// it has a 1-arg constructor that takes an Int
class Circle(r:Int) {
// define a read-only field
val radius = r;
// define a method to compute diameter
def diameter = radius * 2
// define a method to compute area
// we use braces since we need more than one line of code
def area = {
// declare a constant (think "val"ue)
val pi = 3.14
// declare a variable
var area = pi * radius
area *= radius
// the braces are really an expression, and the
// last statement dictates the value of the expression
// so, no need to "return"
area
}
// override a superclass method, like @Override in Java
// we actually can't compile without this
override def toString = "Circle with radius " + radius
}
// This is a type of static singleton; more on that later
object CircleDemo {
def main(args: Array[String]) {
// Create objects as in Java
val circle = new Circle(4)
println(circle.toString)
println(circle.diameter)
println(circle.radius)
println(circle.area)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment