scala 学习笔记

1.简洁

1.1。java的写法

class MyClass {  
    private int index;  
    private String name;  
    public MyClass(int index, String name) {  
        this.index = index;  
        this.name = name;  
    }  
} 

1.2。scala的写法:写起来更快,读起来更容易,重要的是更不容易犯错

class MyClass(index: Int, name: String) 

2.更灵活,更抽象

假设你有一个String变量name,你想弄清楚是否String包含一个大写字符。

2.1。 java的写法

boolean nameHasUpperCase = false;  
for (int i = 0; i < name.length(); ++i) {  
 if (Character.isUpperCase(name.charAt(i))) {  
  nameHasUpperCase = true;  
  break;  
 }  
} 

或者更近一步:面向接口编程

interface CharacterProperty {  
 boolean hasProperty(char ch);  
}  

实现exists(String name, CharacterProperty property)方法

exists(name, new CharacterProperty {  
 boolean hasProperty(char ch) {  
  return Character.isUpperCase(ch);  
 }  
}); 

2.2。scala的写法

val nameHasUpperCase = name.exists(_.isUpper) 

3.类型推断

3.1

java的static方法无法访问泛型类的类型参数,所以static方法需要使用泛型能力,就必须使其成为泛型方法。

3.2

val x = new HashMap[Int, String]()  
val x: Map[Int, String] = new HashMap()  

或者:

class Complex(real: Double, imaginary: Double) {
    def re() = real
    def im() = imaginary
}

需要注意的是,这两个方法的返回值都没有显式定义。在编译过程中,编译器可以根据函数的定义来推断出:两个函数的返回值都是Double类型。

其他:

scala> def id[T](x: T) = x
id: [T](x: T)T

scala> val x = id(322)
x: Int = 322

scala> val x = id("hey")
x: java.lang.String = hey

scala> val x = id(Array(1,2,3,4))
x: Array[Int] = Array(1, 2, 3, 4)

4.无参方法

Complex 类中的re 和im 方法有个小问题,那就是调用这两个方法时,需要在方法名后面跟上一对空括号,就像下面的例子一样:

object ComplexNumbers {
  def main(args: Array[String]) {
    val c= new Complex(1.2, 3.4)
    println("imaginary part: " + c.im())
  }
}

如果能够省掉这些方法后面的空括号,就像访问类属性一样访问类的方法,则程序会更加简洁。这在Scala 中是可行的。

 

class Complex(real: Double, imaginary: Double) {
  def re = real
  def im = imaginary
}

 

原文地址:https://www.cnblogs.com/yuyutianxia/p/4198735.html