注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

阿弥陀佛

街树飘影未见尘 潭月潜水了无声 般若观照心空静...

 
 
 

日志

 
 
关于我

一直从事气象预报、服务建模实践应用。 注重气象物理场、实况场、地理信息、本体知识库、分布式气象内容管理系统建立。 对Barnes客观分析, 小波,计算神经网络、信任传播、贝叶斯推理、专家系统、网络本体语言有一定体会。 一直使用Java、Delphi、Prolog、SQL编程。

网易考拉推荐

scala 编程rules  

2013-09-27 03:46:48|  分类: Scala |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |


参见scala in depth, 该书给出了scala编程的28条规则,通过这些规则的学习、实践领会可以使自己成为合格的scala程序员。
Josh Suereth
Automatic-Resource-Management
ManagedResource
1. Experiment in the REPL(Read Eval Print Loop)
Scala provides the REPL tool so every developer can toy around in the language before committing
any final code. It’s by far the most useful tool in the Scala ecosystem. Development should
start inside the REPL in Scala.

2.Use expressions not statements
In Scala, a lot of code can be written as small methods of one expression. This style is not only
elegant, but helps in code maintenance.
 A statement is something that executes; an expression is something that evaluates to a value.

Think in expressions
scala> if(true) "true string" else "false string"
res10: String = true string

Don’t use return
def createErrorMessage(errorCode: Int) : String = errorCode match {
   case 1 => "Network Failure"
   case 2 => "I/O Failure"
   case _ => "Unknown Error"
}

3. Prefer Immutability
Creating immutable classes drastically reduces the number of potential runtime issues. When in
doubt, it’s safest to stay immutable.

4.Use None instead of null
While it was habit in Java to initialize values to null, Scala provides an Option type for the same
purpose. Option is self-documenting for developers and, used correctly, can prevent unintended
null pointer exceptions when using Scala.
scala> var x : Option[String] = None
x: Option[String] = None
scala> x.get
java.util.NoSuchElementException: None.get in
scala> x.getOrElse("default")
res0: String = default
scala> x = Some("Now Initialized")
x: Option[String] = Some(Now Initialized)
scala> x.get
res0: java.lang.String = Now Initialized
scala> x.getOrElse("default")
res1: java.lang.String = Now Initialized
An Option containing no value can be constructed via the None object. An Option that
contains a value is created via the Some factory method. Option provides many differing
ways of retrieving values from its inside. Of particular use are the get and
getOrElse methods. The get method will attempt to access the value stored in an
Option and will throw an exception if it’s empty. This is similar to accessing nullable
values within other languages. The getOrElse method will attempt to access the value
stored in an Option, if one exists; otherwise it will return the value supplied to the
method. You should always prefer getOrElse over using get.

def getTemporaryDirectory(tmpArg: Option[String]): java.io.File = {
  tmpArg.map(name => new java.io.File(name)).
  filter(_.isDirectory).
  getOrElse(new java.io.File(System.getProperty("java.io.tmpdir")))
}

def createConnection(conn_url: Option[String],
  conn_user: Option[String],
  conn_pw: Option[String]) : Option[Connection] =
  for {
    url <- conn_url
    user <- conn_user
    pw <- conn_pw
  } yield DriverManager.getConnection(url, user, pw)
可以用更抽象的方式建立数据库连接:
scala> def lift3[A,B,C,D](
 f: Function3[A,B,C,D]): Function3[Option[A], Option[B], Option[C], Option[D]] = { (oa : Option[A], ob : Option[B], oc : Option[C]) =>
    for(a <- oa; b <- ob; c <- oc) yield f(a,b,c)
 }
lift3: [A,B,C,D](f: (A, B, C) => D)(Option[A],Option[B],Option[C]) => Option[D]
scala> lift3(DriverManager.getConnection)
res4: (Option[java.lang.String],Option[java.lang.String],Option[java.lang.String]) => Option[java.sql.Connection] =<function3>

5. Use scala.Equals for polymorphic equality
Polymorphic equality is easy to mess up. scala.Equals provides a template to make it easier to avoid mistakes.
trait InstantaneousTime extends Equals {
  val repr: Int
  override def canEqual(other: Any) = other.isInstanceOf[InstantaneousTime]
  override def equals(other: Any) : Boolean = other match {
    case that: InstantaneousTime =>if(this eq that) true else {
        (that.## == this.##) &&
        (that canEqual this) &&
        (repr == that.repr)
     }
     case _ => false
   }
   override def hashCode(): Int = repr.hashCode
}
trait Event extends InstantaneousTime {
  val name: String
  override def canEqual(other: Any) = other.isInstanceOf[Event]
  override def equals(other: Any): Boolean = other match {
     case that: Event => if(this eq that) {
        true
     } else {
       (that canEqual this) &&
       (repr == that.repr) &&
       (name == that.name)
     }
    case _ => false
  }
}
## method is equivalent to  the hashCode method in Java
.
  评论这张
 
阅读(496)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017