public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
object ScalaSingleton {
def printSomething() {
println("printSomething")
}
}
class ScalaConstructorExample(val x: Double, y: String) {
println(x + y)
}
public class ScalaConstructorExample
{
private final double x;
public double x()
{
return this.x;
}
public ScalaConstructorExample(double x, String y)
{
Predef..MODULE$.println(new StringBuilder().append(x).append(y).toString());
}
}
abstract class Plant {
def photosynthesis = println("Oh, the sunlight!")
}
class Rose extends Plant {
def smell = println("Good!")
def makePeopleHappy = println("People like me")
}
class Ruderal extends Plant {
def grow = println("I take up all the space!")
}
abstract class Animal {
def move = println("I can move!")
}
class Dog extends Animal {
def bark = println("Woof!")
def makePeopleHappy = println("People like me")
}
class Snake extends Animal {
def bite = println("I am poisonous!")
}
对继承体系下手,抽取公共父类,将共同行为置于其中。
创建一个接口,将共同行为声明于其中。同时提供一个静态方法,来实现共同行为。每一个实现该接口的类,都调用该静态方法。
trait PeoplePleaser {
def makePeopleHappy = println("People like me")
}
class Rose extends Plant with PeoplePleaser {
def smell = println("Good!")
}
class Dog extends Animal with PeoplePleaser {
def bark = println("Woof!")
}
private String str = null;
public String getStr() {
if (str == null) {
str = getStrFromWebService();
}
return str;
}
private Lazy<String> str = new Lazy<string> (() => GetStrFromWebService ());
public String Str
{
get
{
return str.Value;
}
}
lazy val str = getStrFromWebService()
abstract class Animal
case class Cat(name: String) extends Animal
case class Dog(name: String) extends Animal
Animal animal = createAnimal();
String result = "other animal";
if (animal instanceof Dog) {
result = "this is a dog";
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
if (cat.name() == "kitty") {
result = "this is a cat named kitty";
}
}
return result;
val animal = createAnimal
animal match {
case Dog(anyName) => "this is a dog"
case Cat("kitty") => "this is a cat named kitty"
case _ => "other animal"
}
class Duck {
def makeDuckNoise() = "gua gua"
}
class Chicken {
def makeChickenNoise() = "ge ge"
}
def giveMeADuck(duck: Duck) = duck.makeDuckNoise()
giveMeADuck(new Duck)
class Ducken(chicken: Chicken) extends Duck {
override def makeDuckNoise() = chicken.makeChickenNoise()
}
giveMeADuck(new Ducken(new Chicken))
implicit def chickenToDuck(chicken: Chicken) = new Ducken(chicken)
giveMeADuck(new Chicken)
def calculateTotal: Option[Int] = {
val price: Option[Int] = getPrice
val amount: Option[Int] = getAmount
if (price.isEmpty || amount.isEmpty) {
None
} else {
Some(price.get * amount.get)
}
}
def calculateTotalWithFor: Option[Int] = {
for (price <- getPrice; amount <- getAmount) yield price * amount
}