Scala笔记

原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11540972.html

Scala学习笔记

import Array._

/**
 * TODO
 * scala 基础用法
 */
object Hello {

  println("hello world ! scala ")

  def main(args: Array[String]){
    println("hello world ! main ")
    println(o(4))
  }

  def m(x : Int) = x + 3

  val f = (x : Int) => x + 3

  def n(x : Int, y : String) : String = x + 3 + ""

  def o(x : Int) : String = {
    var duc : Int = 0
    duc = x /(2)
    return duc + ""
  }

  var factor = 3
  var multiper = (i : Int) => i * factor

  var z : Array[String] = new Array[String](3)

  var zz = new Array[String](3)

  var zzz = Array("x", "y", "z")

  for (t <- zzz){
    println("for1" + t)
  }

  for (t <- 1 until zzz.length){
    println("for2" + t)
  }

  var myMatrix = ofDim[Int](3, 3)

  for (i <- 0 to 2){
    for (j <- 0 to 2){
      myMatrix(i)(j) = j
    }
  }

  for (i <- 0 to 2){
    for (j <- 0 to 2){
      print(" " +   myMatrix(i)(j))
    }
    println()
  }

  var list : List[Any] = List(
    "a string",
    732,
    'c',
    true,
    () => "an anonymous function returning a string"
  )

  list.foreach(element => println(element))

  class User
  var user1 = new User

  class Point(var x : Int, var y : Int) {

    def mov(dx : Int, dy : Int): Unit ={
      x = x + dx
      y = y + dy
    }

    override def toString: String = s"($x, $y)"
  }

  var point = new Point(3, 4)
  point.x
  point.y
  println(point)

  class PointA  {
    private var _x : Int = 0
    private var _y : Int = 0
    private val bound : Int = 100

    def x = _x
    def x_= (newValue : Int) : Unit = {
      if (newValue < bound) _x = newValue else printWarning
    }

    def y = _y
    def y_= (newValue: Int): Unit = {
      if (newValue < bound) _y = newValue else printWarning
    }

    private def printWarning = println("WARNING: Out of bounds")

  }

  var pointA = new PointA
  pointA.x = 6
  pointA.y = 8
  println(pointA.x)
  println(pointA.y)
  pointA.x_=(45)
  pointA.y_=(101)

  trait Parent[A] {
    def print(hello : A) : String
  }

  trait ParentB[B] {
    def print(hello : B) : String
    def hasNext : Boolean
    def next() : B
  }

  class Son(to : Int) extends ParentB[Int] {
    def next(xxx: Unit) = Unit


    private var current : Int = 0

    override def print(hello: Int): String = "print hello"

    override def hasNext: Boolean = current < to

    override def next(): Int = {
      if (hasNext){
        val t = current
        current += 1
        t
      } else 0
    }
  }

  var son = new Son(10)
  for (i <- 0 to 2) {
    println(son.next())
  }
  son next println

  var tupple = ("hello", 20) : Tuple2[String, Int]
  println(tupple._1)
  println(tupple._2)

  /**
   * 解构
   */
  val (name, age) = tupple
  println(name)
  println(age)

  var plan = List(("bob", 88), ("lina", 77), ("cate", 66))
  plan.foreach(tupple => {
    tupple match {
      case ("bob", age) => println(s"bob is $age years old")
      case p if (p._1 == "lina") => println(s"lina is ${p._2} years old")
      case p if (p._1 == "cate") => println(s"cate is ${p._2} years old")
      case _ => println("No body is here")
    }
  })

}

class Clazz(x : Int, y : Int) {
  var mx = x
  var my = y

  def mov(dx : Int, dy : Int) = {
    mx = mx + dx
    mx = my + dy
    println("x 的坐标点: " + mx)
    println("y 的坐标点: " + my)
  }
}

object test {
  def main(args: Array[String]): Unit = {
    var pt = new Clazz(10, 10)
    pt.mov(14, 24)

  }
}

abstract class A {
  val message : String
}

class B extends A {
  override val message: String = "I'm an instance of class B"
}

trait C extends A {
  def loudMessage = message.toUpperCase()
}

class D extends B with C

object A {
  def main(args: Array[String]): Unit = {
    var d = new D
    println(d.message)
    println(d.loudMessage)
  }
}

abstract class AbsIterator {
  type T
  def hasNext : Boolean
  def next() : T
}

class StringIterator(s : String) extends AbsIterator {
  override type T = Char

  private var i = 0

  override def hasNext = i < s.length

  override def next() = {
    var ch = s charAt(i)
    i += 1
    ch
  }
}

trait RichIterator extends AbsIterator {
  def foreach(f : T => Unit) : Unit = while (hasNext) f(next())
}

object StringIteratorTest extends App {
  class RichStringIter extends StringIterator("Scala") with RichIterator
  var richStringIter = new RichStringIter
  richStringIter foreach println

  var salaries = Seq(200, 300, 400)
  var doubleSalary = (x : Int) => x * 2
  var newSalary = salaries.map(doubleSalary)
  var newSalaryB = salaries.map(x => x * 2)
  var newSalaryC = salaries.map(_ * 2)

}

object salaryRaiserA {
  def smallPromotion(salaries : List[Double]) : List[Double] =
    salaries.map(x => x * 1.1)
  def greatePromotion(salaries : List[Double]) : List[Double] =
    salaries.map(x => x * math.log(x))
  def hugePromotion(salaries : List[Double]) : List[Double] =
    salaries.map(x => x * x)
  private def promotion(salaries : List[Double], promotionFunc : Double => Double) : List[Double] =
    salaries.map(promotionFunc)
  def simplePromotion(salaries : List[Double]) : List[Double] =
    promotion(salaries, x => x * x)
}

def urlBuilder(ssl : Boolean, domainName : String) : (String, String) => String = {
  val schema = if (ssl) "https://" else "http://"
  (endpoint : String, query : String) => s"$schema$domainName/$endpoint?$query"
}

val getUrl = urlBuilder(true, "www.baidu.com");
val endpoint = "users"
val query = "id=1"
val url = getUrl(endpoint, query)

def factorial(x : Int) : Int = {
  def fact(x : Int, accumulator : Int) : Int = {
    if (x <= 1) accumulator
    else fact(x - 1, x * accumulator)
  }
  fact(x, 1)
}

abstract class Notification
case class Email(sender : String, title : String, body : String) extends Notification
case class SMS(caller : String, message : String) extends Notification

def showNotification(notification : Notification) : String = {
  notification match {
    case Email(sender, title, _) =>
      s"You got an email from $sender with title: $title"
    case SMS(caller, message) if message.contains("have") =>
      s"You got an SMS from $caller! Message: $message"
  }
}

val email = Email("me", "good night", "nothing")
val sms = SMS("tailor", "have nothing")
showNotification(email)
showNotification(sms)

abstract class Device
case class Phone(model: String) extends Device {
  def screenOff = "Turning screen off"
}
case class Computer(model: String) extends Device {
  def screenSaverOn = "Turning screen saver on..."
}

def goIdle(device: Device) = device match {
  case p: Phone => p.screenOff
  case c: Computer => c.screenSaverOn
}

//子类必须和基类在同一个包
sealed abstract class sealedA
sealed trait sealedB

class sealedContainer[P <: sealedB](p : P) {
  def pet : P = p
}

class sealedContainerB[P >: sealedB](p : P) {
  def pet : P = p
}

trait Cloneable extends java.lang.Cloneable {
  override def clone(): Cloneable = super.clone().asInstanceOf[Cloneable]
}

trait Resetable {
  def reset : Unit
}

//复合类型
def cloneAndReset(obj : Cloneable with Resetable) : Cloneable = {
  val cloned = obj.clone()
  obj.reset
  cloned
}

//自类型
trait User {
  def username: String
}

trait Tweeter {
  this: User =>  // 重新赋予 this 的类型
  def tweet(tweetText: String) = println(s"$username: $tweetText")
}

class VerifiedTweeter(val username_ : String) extends Tweeter with User {  // 我们混入特质 User 因为 Tweeter 需要
  def username = s"real $username_"
}

val realBeyoncé = new VerifiedTweeter("Beyoncé")
realBeyoncé.tweet("Just spilled my glass of lemonade")  // 打印出 "real Beyoncé: Just spilled my glass of lemonade"

import _root_.com
原文地址:https://www.cnblogs.com/fanerwei222/p/11540972.html