【问题标题】:Declare var in Scala not as either null or None在 Scala 中声明 var 不是 null 或 None
【发布时间】:2019-04-17 13:29:36
【问题描述】:

所以我有一个特征,我需要有具体的成员变量。不过,这些变量是通过 init 方法赋值的。因此,当我声明它们时,我必须将它们分配为空。另一种选择是使用 None,但我必须将它们声明为 Option[T],我也不想要。

所以,我的问题是,我可以在 Scala 中将尚未分配的 var 声明为既不是 null 也不是 None 吗?

【问题讨论】:

  • 是否有充分的理由不使用abstract class 而不是trait?
  • 为什么不让 init 方法实例化只包含不可变值的特征呢?我看到你有 C 背景,但对于 Scala 来说,这种编码风格是非常不鼓励的。
  • @MarkusAppel 你能举个例子吗?
  • @MetallicPriest 类似this。
  • 但是你没有使用我需要的特质。

标签: scala


【解决方案1】:

我的第一次尝试是使用abstract class:

abstract class Test(arg1: Int, arg2: String) {

   val calculatedInConstructor1 = ??? // use args here
   val calculatedInConstructor2 = ??? // use args here
}

new Test(1, "test") {}

如果由于某种原因这是不可能的,那么我仍然可以使用类似的方法来实现:

trait Test {

  // have to be provided in implementation
  protected val arg1: Int
  protected val arg2: String

  // lazy will defer initialization so you can provide
  // arg1 and arg2 in class extending Test
  lazy val calculatedOnFirstUse1 = ??? // use args here
  lazy val calculatedOnFirstUse2 = ??? // use args here
}

new Test {
  val arg1 = 1
  val arg2 = "test"
}

没有理由使用vars、nulls 等。

【讨论】:

    【解决方案2】:

    您可以将它们定义为方法:

     trait Test {
    
      def arg1: Int
      def arg2: String
    
    }
    
    val x=new Test {
      def arg1=1
      def arg2 = "test"
    }
    

    你也可以覆盖为 val

    val y=new Test {
      val arg1=2
      val arg2="test2"
    }
    
    val z= new Test{
      val arg1=3 // won't compile
    }
    x.arg1
    x.arg2
    y.arg1
    y.arg2
    

    【讨论】:

    • 我需要在扩展类中使用它们。
    猜你喜欢
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 2018-09-19
    • 2014-04-25
    • 1970-01-01
    • 2012-07-17
    • 2011-09-28
    • 1970-01-01
    相关资源
    最近更新 更多