加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

oop – Scala:匹配案例类

发布时间:2020-12-16 08:57:49 所属栏目:安全 来源:网络整理
导读:以下代码声称杰克受雇于建筑业,但简是另一个粗暴经济的受害者: abstract class Person(name: String) { case class Student(name: String,major: String) extends Person(name) override def toString(): String = this match { case Student(name,major) =
以下代码声称杰克受雇于建筑业,但简是另一个粗暴经济的受害者:

abstract class Person(name: String) {

  case class Student(name: String,major: String) extends Person(name)

  override def toString(): String = this match {
    case Student(name,major) => name + " studies " + major
    case Worker(name,occupation) => name + " does " + occupation
    case _ => name + " is unemployed"
  }
}

case class Worker(name: String,job: String) extends Person(name)

object Narrator extends Person("Jake") {
  def main(args: Array[String]) {
    var friend: Person = new Student("Jane","biology")
    println("My friend " + friend) //outputs "Jane is unemployed"
    friend = new Worker("Jack","construction")
    println("My friend " + friend) //outputs "Jack does construction"
  }
}

为什么比赛未能将Jane视为学生?

解决方法

埃米尔是完全正确的,但这是一个明确的例子:

scala> case class A(a: String) {
     |   case class B(b: String)
     |   def who(obj: Any) = obj match {
     |     case B(b) => println("I'm A("+a+").B("+b+").")
     |     case b: A#B => println("I'm B("+b+") from some A")
     |     case other => println("Who am I?")
     |   }
     | }
defined class A

scala> val a1 = A("a1")
a1: A = A(a1)

scala> val a2 = A("a2")
a2: A = A(a2)

scala> val b1= a1.B("b1")
b1: a1.B = B(b1)

scala> val b2 = a2.B("b2")
b2: a2.B = B(b2)

scala> a1 who b1
I'm A(a1).B(b1).

scala> a1 who b2
I'm B(B(b2)) from some A

更确切地说,这一行:

case Student(name,major) => name + " studies " + major

真正意思

case this.Student(name,major) => name + " studies " + major

不幸的是,虽然Jane在Jake身上实例化,但在Jane的案例中,这指的是Jane自己.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读