为什么没找到这个课程?

时间:2014-10-07 20:36:47

标签: scala inner-classes

在scala计划中,我根据 http://danielwestheide.com/blog/2012/11/21/the-neophytes-guide-to-scala-part-1-extractors.html

的一些摘要创建了一个与用户匹配的案例

特别是,我已经宣布了一个扩展另一个类的类,然后我试图对该类进行大小写匹配。

user match {
  case FreeUser(name) => "Hello " + name;
  case PremiumUser(name) => "hello " + name;
}

这些操作都失败了:好像case子句似乎没有看到FreeUser和PremiumUser类的类定义,它们就在它上面。

class FreeUser(val name: String) extends User{
  def unapply(user: FreeUser):Option[String] = Some(user.name);
}

//takes the object as input, returns the parameter used to construct it.
class PremiumUser(val name: String) extends User {
  def unapply(user: PremiumUser):Option[String]= Some(user.name);
}
val name = "ASDF"
val user: User = new PremiumUser("jay");
user match {
  /** This statement fails to comiple : not found, value FreeUser. **/
  case FreeUser(name) => "Hello " + name;
  case PremiumUser(name) => "hello " + name;
}

对于完整的课程,您可以参考这个要点。 https://gist.github.com/anonymous/e96107f91ef0262f3268

因此,我的问题是如何引用Scala中case子句中的内部类。

2 个答案:

答案 0 :(得分:4)

freeUser和PreimumUser类都应该是case类,如下所示;

/**
 * Why does FreeUser fail to compile?
 */
object Sytax {

  object Thrice {
       def apply(x : Int) : Int = x *3
       def unapply(z : Int) : Option[Int] = if (z%3==0) Some(z/3) else None
  }

  val x = Thrice(3);

  trait User {
    def name:String;
  }

  case class FreeUser(val name: String) extends User{
    def unapply(user: FreeUser):Option[String] = Some(user.name);
  }

  //takes the object as input, returns the parameter used to construct it.
  case class PremiumUser(val name: String) extends User {
    def unapply(user: PremiumUser):Option[String]= Some(user.name);
  }
  val name = "ASDF"
  val user: User = new PremiumUser("jay");
  user match {
    case FreeUser(name) => "Hello " + name;
    case PremiumUser(name) => "hello " + name;
  }
}

答案 1 :(得分:2)

必须在配套对象中定义unapply方法:

object FreeUser {
  def unapply(user: FreeUser):Option[String] = Some(user.name);
}

object PremiumUser {
  def unapply(user: PremiumUser):Option[String]= Some(user.name);
}

我现在无法找到关于你为什么不能在课堂上取消申请的官方消息,我认为这是因为课堂上的匹配隐含地调用SomeObject.unapply并且这样做它不能成为一个班级(你必须做new SomeClass.unapply,单身就好了。)