1.String 插入引用(需要在引用的变量前增加 s 标识)
val name="jiang"
val info=s"i am $name"
info: String = i am jiang
val age0=19
val str1=s"i am ${age0 + 1} years old"
str1: String = i am 20 years old
// 同样也能在类中使用
case class User(name:String,age:Int)
val user1=User("jiang",20)
println(s"${user1.name} is ${user1.age} years old")
//jiang is 20 years old2.scala 正则表达式的使用
scala> val numPattern="[0-9]+".r numPattern: scala.util.matching.Regex = [0-9]+ scala> val address="123 Main Street Suite 101" address: String = 123 Main Street Suite 101 scala> numPattern.findFirstIn(address) res4: Option[String] = Some(123)
3. trait 中继承方法或者参数的变量定义参数(var 和val差异)
val 继承的方法重写需要加overide
var 不需要
trait Person{
var name:String
val age=14
}
class Jiang extends Person{
var name="jiang"
override val age=19
}4.Either 用法 -- 9/26
Either 相对于if else ------> Either返回值Left Right 可以不一致,返回值可以定义。if else 不同的返回值则为Any.
def eitherDemo(x:Int):Either[Int,String] = if(x>10) Left(2) else Right("Big Nim")
scala: eitherDemo(15)
res15: Either[Int,String] = Left(2)
//--------------------------//
def ifDemo(x:Int) = if(x>2) 2 else "jiang"
scala> ifDemo(15)
res0: Any = 25.reduce 与fold差异简单说明 --9/28
reduce 的返回值必须和列表元素的返回值一致或者是父类,fold 无此限制但fold必须初始化其折叠值
List("1", "2", "3").foldLeft(0)((a, b) => a.toInt + b.toInt) =>res0: Int = 6
List("1", "2", "3").reduceLeft((a, b) => a.toInt + b.toInt) =>报错,类型不一致错误
---> 正确写法:List("1", "2", "3").reduceLeft(_+_)6.what‘s meaning of type MyType = Int =>Boolean? --9/28
先来看一个例子
type MyType = Int =>Boolean def isTrue(x:Int) = x>0 val fun: MyType = isTure
定义一个参数为Int 返回值为Bollean 的类型值,type 赋予其别名为MyType.
可以说成fun的返回值须是一个由f(x:Int)函数生成的Boolean 值. stackoverflow
7.
val VulnerableVersions = Set( "2.0", "2.0.1", "2.0.2", "2.0.3", "2.0.4", "2.0.5","2.1", "2.1.1", "2.1.2")
val version = Option("2.1")
val result = version.filter(VulnerableVersions)Option 的Api中filter方法: final def filter(p:(A)=>Boolean):Option[A]
本例是不是看起来很奇怪,判断内容应该为Boolean 实际却是一个Set集合?
-->实际上 Set[A] extends A=>Boolean 得到的结果返回一个true 或者 getOrElse
原文:http://my.oschina.net/jinfu/blog/515222