scala中类的简单使用记录
Posted yxj0728
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scala中类的简单使用记录相关的知识,希望对你有一定的参考价值。
import scala.collection.mutable.ArrayBuffer /** * scala 中内部类的使用 */ class Classes { class Stu(name:String , age:Int) {} val stus = new ArrayBuffer[Stu] def getStu(name:String) = { new Stu(name , 0) } } object ClazTest{ def main(args: Array[String]): Unit = { // 需要注意 val c1 = new Classes val stu1 =c1.getStu("yxj") c1.stus += stu1 println(stu1) val c2 = new Classes val stu2 = c2.getStu("yxj") c2.stus += stu2 println(stu2) // 下面将类stu1添加到c2中是不允许的,会报错 // c2.stus += stu1 // 他们toString时打印的hashcode是不同的 // [email protected] //[email protected] } }
/** * scala 中类的使用 */ class HelloWorld { var sex = "" private var name = "yxj" def sayHello(): Unit ={ println("hello " + name) } def getName = name } object HelloTest { def main(args: Array[String]): Unit = { val hello = new HelloWorld hello.sayHello() hello.sex = "male"; println(hello.sex) val s1 = new Student s1.age = 30 val s2 = new Student s2.age = 20 println(s1.older(s2)) // 返回true // 使用 private[this] myage 只能在本类中使用, } }
class Student { private var myAge = 0 def age_=(newAge : Int): Unit ={ if(newAge > myAge) myAge = newAge else println("illegal age!!!") } def age = myAge def older(s : Student) = { myAge > s.myAge } }
import scala.beans.BeanProperty class LikeJavaClaz { @BeanProperty var name = "" } object LikeJavaClazTest { def main(args: Array[String]): Unit = { val likeJavaClaz = new LikeJavaClaz likeJavaClaz.setName("yexj") println(likeJavaClaz.name) println(likeJavaClaz.getName) } }
以上是关于scala中类的简单使用记录的主要内容,如果未能解决你的问题,请参考以下文章