欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

scala 基础入门

程序员文章站 2022-06-17 16:05:45
...

 

scala 安装入门

http://knight-black-bob.iteye.com/blog/2286188

 

helloworld

package com.baoy.cn.demo

 object   Hello { 
  def main(args: Array[String]){
    println("hello world")
  }
}

 

 类对象

package com.baoy.cn.demo

trait Equals {
   def isEqual(x: Any): Boolean
   def isNotEqual(x: Any): Boolean = !isEqual(x)
}

 

package com.baoy.cn.demo

class Student(val name: String, val password: String) extends Equals{
  var xname: String = name
  var xpassword: String = password

  def toString1(): Unit = {
    println("Strudent:[name:" + xname + ",password:" + xpassword + "]")
  }

  override def toString(): String = {
    "Strudent:[name:" + xname + ",password:" + xpassword + "]"
  }

   def isEqual(obj: Any) ={
    obj.isInstanceOf[Student] &&
    obj.asInstanceOf[Student].xname == xname
  }
  
}

object Student {
  def main(args: Array[String]): Unit = {
    val stu = new Student("baoyou", "123456")
    stu.toString1()
    println(stu.toString())
    
    val stu2 = new Student("baoyou", "1234567")
    
    val bool = stu2.isEqual(stu)
    println(bool)
  }
}

 

for

package com.baoy.cn.demo

class ForDemo {
   
 
}

object ForDemo{
  def main(args: Array[String]){
    println("-------------------------------- i <- 0 to 9")
    var result = ""
    for (i <- 0 to 9) {
      result += i + " "
    }
    println(result)
    println("-------------------------------- i <- 0 until 10")
    result = ""
    for (i <- 0 until 10) {
      result += i + " "
    }
    println(result)
    println("-------------------------------- i <- Range(0, 10)")
    result = ""
    for (i <- Range(0, 10)) {
      result += i + " "
    }
    println(result)
    println("-------------------------------- i <- Range(0, 20, 2)")
    result = ""
    for (i <- Range(0, 20, 2)) {
      result += i + " "
    }
    println(result) 
  }
}

 

vector

package com.baoy.cn.demo

class VectorDemo {

}

object VectorDemo {
  def main(args: Array[String]) {
       val v1= Vector(1,2,3,4,5)
       println(v1)
       var result = ""
       for(i <- v1 ){
         result += i + " "
       }
       println(result)
       val v2 = v1.reverse
       println(v2)
       
       var v3 = v2.sorted
       println(v3)
       
  }
}

 

collection

package com.baoy.cn.demo
 

class CollectionDemo {

}

object CollectionDemo {
  def main(args: Array[String]): Unit = {
    //1 . List
    // List of Strings
    val fruit: List[String] = List(  "oranges", "pears","apples")

    // List of Integers
    val nums: List[Int] = List(1, 2, 3, 4)

    // Empty List.
    val empty: List[Nothing] = List()

    // Two dimensional list
    val dim: List[List[Int]] =
      List(
        List(1, 0, 0),
        List(0, 1, 0),
        List(0, 0, 1))

    // List of Strings
    val fruit2 = "apples" :: ("oranges" :: ("pears" :: Nil))

    // List of Integers
    val nums2 = 1 :: (2 :: (3 :: (4 :: Nil)))

    // Empty List.
    val empty2 = Nil

    // Two dimensional list
    val dim2 = (1 :: (0 :: (0 :: Nil))) ::
      (0 :: (1 :: (0 :: Nil))) ::
      (0 :: (0 :: (1 :: Nil))) :: Nil

      
      for( i <- 0 to fruit.length -1 ){
        print (fruit.apply(i) + " ")
      }
      println()
      fruit.foreach { x => print(x +" ") }
      println()
      println(fruit.contains("oranges"))
      val it = fruit.toIterator
      while (it.hasNext) {
        print(it.next() + " ")
      }
      println()
      println(fruit.mkString(","))
      
      val fruit3 = fruit.sortWith(_.compareTo(_) < 0)
      fruit3.map { s => print(s + " ") }
    }
}

 

yield

package com.baoy.cn.demo

import scala.collection.immutable.Vector

class YieldDemo {
  
}
object YieldDemo{
  def main(args: Array[String]): Unit = {
 
    val v= Vector(1,2,3,4,5,6,7,8,9,10,11,12,13,14,17)
    val v1 = yielding(v);
    println(v1)
     val v2 = evenGT5(v)
     println(v2)
  }
  
  def yielding( v : Vector[Int] ): Vector[Int] = {
    val result = for{
      n <- v 
      if n < 10
      if n %2 != 0
    } yield {n} // yield 交出 n
    result
  }
  
  def evenGT5( v : Vector[Int] ): Vector[Int] = {
     var result = Vector[Int]()
     for{
      n <- v 
      if n < 10
      if n %2 == 0
    }    result = result :+ n  
    result
  }
  
}

 

split

package com.baoy.cn.demo
 

class SplitDemo {
  
  def apply(userId:String ,domain:String)  = {
     userId +"@"+ domain
  }
  
  def unapply(str: String): Option[(String, String)] = {
      val parts = str split "@"
      if (parts.length == 2){
         Some(parts(0), parts(1)) 
      }else{
         None
      }
   }
  
  def show(x: Option[String]) = x match {
      case Some(s) => s 
      case None => "?"
   }
  
  
}
object SplitDemo{
  def main(args: Array[String]): Unit = {
    val sd = new SplitDemo().apply("curiousby","163.com")
    val sdd = new SplitDemo().unapply(sd) 
    println(sdd.isEmpty) 
    
    val it = sdd.iterator
    while (it.hasNext){
         println(it.next()._1)
      }
    
    /* val n = sdd.map{ n => n }
    println(n)*/
    
    println( Some("1","2","3","4","5").iterator.next()._5)
    
    
    
    
  }
}

 

map reduce foreach

package com.baoy.cn.demo

import scala.collection.immutable.Vector
 
object MapReduceForeachDemo {
  def main(args: Array[String]): Unit = {
   val v =Vector(1,2,3,4)
    println(v)
   val v2 =  v.map{ n => n+1 }
   println(v2)
   
  var  sum =0  
  v2.foreach(x => sum += x)
  println(sum)
   
  
  val sum2 = v2.reduce((sum2,n) => sum + n)
  println(sum) 
  
  }
}

class MapReduceForeachDemo{
  
}

 

regex

package com.baoy.cn.demo

import scala.util.matching.Regex

class RegexDemo {
  
}

object RegexDemo{
  def main(args: Array[String]): Unit = {
      val pattern = new Regex("(S|s)cala")
      val str = "Scala is scalable and cool"
      var string = pattern findFirstIn str
      println(string )
      
      var string2 = pattern findAllIn str
      println(string2)
      
      var string3 =string2.mkString(",")
      println(string3)
      
  }
}

 

File

package com.baoy.cn.demo

import scala.io.Source
import java.io.PrintWriter
import java.io.File

class FileDemo {

}

object FileDemo {
  def main(args: Array[String]): Unit = {

    val wstr = Console.readLine()
    //println(wstr)

    val writer = new PrintWriter(new File("C:\\Users\\cmcc-B100036\\Desktop\\test.txt"))
    writer.write(wstr)
    writer.close()

    Source.fromFile("C:\\Users\\cmcc-B100036\\Desktop\\test.txt").foreach {
      print
    }
  }
}

 

abstract

package com.baoy.cn.mabstract
 

abstract class Cat   {
  def color():Unit
}

object Cat{
  def main(args: Array[String]): Unit = {
    val cat1 = new Garfield()
    val cat2 = new Doraemon()
    cat1.color()
    cat2.color()
  }
}




package com.baoy.cn.mabstract

class Doraemon extends Cat{
  def color():Unit={
    print("blue")
  }
}




package com.baoy.cn.mabstract

class Garfield extends Cat{
  
  def color():Unit = {
    println("brown")
  }
}

 

 enumeration

package com.baoy.cn.demo
 
class Level{
 
}

object Level extends Enumeration{
  type Level = Value
  val overflow ,high,medium,low,empty = Value
  
  def main(args: Array[String]): Unit = {
    val v =  {
      for(n <- Range(0,Level.maxId))
      yield (n,Level(n)) 
      }
    
    println(v) 
    
    checkLevel(overflow)
    
     val v2=  {
      for(lev <- Level.values)
      yield lev 
      }
    print(v2.toIndexedSeq)
  }
   def checkLevel(level:Level)= level match  {
    case overflow => println("overflow --- ")
    case high => println("high --- ")
    case medium => println("medium --- ")
    case low => println("low --- ")
    case empty => println("empty --- ")
  }
}


 

 scala  隐式转换

package com.baoy.cn.demo

class Implicit{
  
}

class A{
   def a{
    println("so a......")
  }
}

class RichA(a:A){
  def rich{
    println("so rich......")
  }
}

object Implicit { 
	
  def main(args: Array[String]): Unit = {
		implicit def a2RichA(a: A) = new RichA(a)
    val a = new A
    a.rich
    a.a
    
    val b = new RichA( new A)
    b.rich
  
   def testParam(implicit name: String){
    println(name)
   }
  
  implicit val name = "implicited"
  
  testParam
  }
  
  
  
  
   
}

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。


scala 基础入门
            
    
    博客分类: scala scala基础入门 scala 基础入门
            
    
    博客分类: scala scala基础入门 scala 基础入门
            
    
    博客分类: scala scala基础入门 
 
 
 谢谢您的赞助,我会做的更好!