Scala 面向对象-扩展
1 类型检查和转换
1)说明
(1)obj.isInstanceOf[T]:判断 obj 是不是 T 类型。
(2)obj.asInstanceOf[T]:将 obj 强转成 T 类型。
(3)classOf 获取对象的类名。
2)案例实操
class Person{
}
object Person {
def main(args: Array[String]): Unit = {
val person = new Person
//(1)判断对象是否为某个类型的实例
val bool: Boolean = person.isInstanceOf[Person]
if ( bool ) {
//(2)将对象转换为某个类型的实例
val p1: Person = person.asInstanceOf[Person]
println(p1)
}
//(3)获取类的信息
val pClass: Class[Person] = classOf[Person]
println(pClass)
}
}
2 枚举类和应用类
1)说明
枚举类:需要继承 Enumeration
应用类:需要继承 App
2)案例实操
object Test {
def main(args: Array[String]): Unit = {
println(Color.RED)
}
}
// 枚举类
object Color extends Enumeration {
val RED = Value(1, "red")
val YELLOW = Value(2, "yellow")
val BLUE = Value(3, "blue")
}
// 应用类
object Test20 extends App {
println("xxxxxxxxxxx");
}
3 Type 定义新类型
1)说明
使用 type 关键字可以定义新的数据数据类型名称,本质上就是类型的一个别名
2)案例实操
object Test {
def main(args: Array[String]): Unit = {
type S=String
var v:S="abc"
def test():S="xyz"
}
}