• Scala 多继承问题


    多继承问题:

    object LoadIssueDemo extends App {
    
      import java.io.PrintWriter
    
      trait Logger {
        def log(msg: String): Unit
      }
    
      trait FileLogger extends Logger {
        val fileName: String
        val fileOutput = new PrintWriter(fileName: String)
        fileOutput.println("#")
    
        def log(msg: String): Unit = {
          fileOutput.print(msg)
          fileOutput.flush()
        }
      }
    
      class Person
    
      class Student(var name: String) extends Person with FileLogger {
        override val fileName: String = "file.log"
    
      }
    
      new Student("Win").log("trait demo")
    
    }
    

    运行结果:

    原因:fileName还未初始化,就被方法调用。

    解决方法:

    1. 提前定义 (代码不够优雅)

    object PreDefineDemo  extends App{
      import java.io.PrintWriter
    
      trait Logger{
        def log(msg: String): Unit
      }
    
      trait FileLogger extends Logger {
        val fileName: String
        val fileOutput = new PrintWriter(fileName: String)
        fileOutput.println("#")
    
        def log(msg: String): Unit ={
          fileOutput.print(msg)
          fileOutput.flush()
        }
      }
    
      class Person
      class Student(var name: String) extends Person with FileLogger{
        override val fileName: String = "file.log"
    
      }
    
      new { override val fileName: String = "file.log"} with Student("Win").log("trait demo")
    
    }
    

    2. 懒加载(推荐)

    object LazyLoadDemo extends App{
      import java.io.PrintWriter
    
      trait Logger{
        def log(msg: String): Unit
      }
    
      trait FileLogger extends Logger {
        val fileName: String
        lazy val fileOutput = new PrintWriter(fileName: String)
    
        def log(msg: String): Unit ={
          fileOutput.print(msg)
          fileOutput.flush()
        }
      }
    
      class Person
      class Student(var name: String) extends Person with FileLogger{
        override val fileName: String = "file.log"
    
      }
    
      val s = new Student("Win")
      s.log("#")
      s.log("Lazy demo")
    
    }
    
  • 相关阅读:
    IntelliJ Idea 快捷键列表
    mysql索引类型和方式
    基本git指令
    idea中deBug方法
    BeanUtils.copyProperties(A,B)使用注意事项
    MySQL字段类型
    JAVA常识1
    Redis在windows下的安装下载
    Netty
    IDEA工具
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/8016449.html
Copyright © 2020-2023  润新知