scala学习一:伴生对象等基础概念

直接上代码,查看相关注释即可

object关键字及方法格式

/**
 * @Description: object: 关键字,声明一个单例对象(伴生对象)
 * @author : lijie
 * @date Date : 2021年10月16日 20:36
 */

object HelloWorld {
  /**
   * main 方法:从外部可以直接调用执行的方法
   * 格式为:
   * def 方法名称(参数名称: 参数类型): 返回值类型={方法体}
   */
  def main(args: Array[String]): Unit = {
    System.out.println("Hello World JAVA")
    System.err.println("Hello World JAVA")
    print("Hello World!")
  }

}

理解伴生对象

/**
 * @Description: 理解伴生对象
 * @author : lijie
 * @date Date : 2021年10月16日 22:22
 */
class Student(name: String, age: Int) {
  def printInfos(): Unit = {
    println("name:" + name, "age" + age, "school:" + school)
  }


}

/**
 * school为类级别的属性,因此可以引入伴生对象来声明
 * 伴生类与伴生对象可以相互调用属性,所以可以调用school
 */
object Student {
  val school: String = "安庆师范"

  def main(args: Array[String]): Unit = {
    val liang = new Student("亮总", 24)
    val zhu = new Student("朱总", 25)
    liang.printInfos()
    zhu.printInfos()
  }
}

String的一般打印

/**
 * @Description:
 * @author : lijie
 * @date Date : 2021年10月17日 21:19
 */
object Test1_String {
  def main(args: Array[String]): Unit = {
  val name: String = "zhangsan"
  val age: Int = 18

    println(s"${age}的${name}在学习scala")

  }

}

scala的文件IO

/**
 * @Description:
 * @author : lijie
 * @date Date : 2021年10月17日 22:09
 */
object Test3_FileIO {
  def main(args: Array[String]): Unit = {
    Source.fromFile("src/main/resources/input.txt").foreach(print)

    val writer = new PrintWriter(new File("src/main/resources/input1.txt"))
    writer.write("hello lijie")
  // 别忘关闭资源 writer.close() } }
原文地址:https://www.cnblogs.com/codehero/p/15418673.html