Scala case class differences and class

In Scala there is case class, which is actually an ordinary class. But it's class and ordinary slightly different, as follows:
  1, initialization when you can not new, of course, you can also add, certain general category need to add new;

scala> case class Iteblog(name : String)
defined class Iteblog
 
scala> val iteblog = Iteblog( "iteblog_hadoop" )
iteblog : Iteblog = Iteblog(iteblog _ hadoop)
 
scala> val iteblog = new Iteblog( "iteblog_hadoop" )
iteblog : Iteblog = Iteblog(iteblog _ hadoop)

  2, toString achieve more beautiful;

scala> iteblog
res 5 : Iteblog = Iteblog(iteblog _ hadoop)

  3, the default implementation of equals and hashCode;

scala> val iteblog 2 = Iteblog( "iteblog_hadoop" )
iteblog 2 : Iteblog = Iteblog(iteblog _ hadoop)
 
scala> iteblog == iteblog 2
res 6 : Boolean = true
 
scala> iteblog.hashCode
res 7 : Int = 57880342

  4, the default is serialized, that is realized Serializable;

scala> class A
defined class A
 
scala> import java.io. _
import java.io. _
 
scala> val bos = new ByteArrayOutputStream
bos : java.io.ByteArrayOutputStream =
 
scala> val oos = new ObjectOutputStream(bos)
oos : java.io.ObjectOutputStream = java.io.ObjectOutputStream @ 4 c 257 aef
 
scala> oos.writeObject(iteblog)
 
scala> val a = new A
a : A = $iwC$$iwC$A @ 71687 b 10
 
scala> oos.writeObject(a)
java.io.NotSerializableException : $iwC$$iwC$A

  5, automatically inherit from scala.Product some function;
  6, parameter case class constructor is public level, we can directly access;

scala> iteblog.name
res 11 : String = iteblog _ hadoop

  7, support for pattern matching;
  in fact, feeling case class should be the most important feature supports pattern matching. This is the only reason we define case class, no wonder Scala official also said: It Makes Sense to only the DEFINE Case classes IF IS Used to pattern matching for decompose the Data Structures.  . Consider the following example:

object TermTest extends scala.App {
   def printTerm(term : Term) {
     term match {
       case Var(n) = >
         print(n)
       case Fun(x, b) = >
         print( "^" + x + "." )
         printTerm(b)
       case App(f, v) = >
         print( "(" )
         printTerm(f)
         print( " " )
         printTerm(v)
         print( ")" )
     }
   }
   def isIdentityFun(term : Term) : Boolean = term match {
     case Fun(x, Var(y)) if x == y = > true
     case _ = > false
   }
   val id = Fun( "x" , Var( "x" ))
   val t = Fun( "x" , Fun( "y" , App(Var( "x" ), Var( "y" ))))
   printTerm(t)
   println
   println(isIdentityFun(id))
   println(isIdentityFun(t))
}

Guess you like

Origin www.cnblogs.com/guoyu1/p/12599575.html