Scala_(5)_隐式转换|并发编程

6 篇文章 0 订阅
3 篇文章 0 订阅

一、隐式转换

1.语法:

implicit def xxxToxxx()
代码1class Person(val name : String)

class Engineer(val name : String, val salary : Double){
    def code = println("coding.....")
}

implicit def person2Engineer(p : Person): Engineer = {
    new Engineer(p.name, 10000)
}

def toCode(p : Person){
    p.code
}

toCode("scala")
代码运行结果:Coding.....
代码2:
class Level(level : Int)

def toWorker(name : String)(implicit level : Level){
    println(name + ":" + level)
}

implicit val level = new Level(8)
toWorker("Spark")
代码3:
object Context_Implicits{
    implicit val default:String = "Flink"
}

object Param{
    def print(content : String)(implicit language : String){
        println("language: " + content)
    }
}

object Implicit_Paramters{
    def main(args : Array[String]){
        param.print("Spark")("Scala")
    }
    
    import Context_Implicits._
    Param.print("Hadoop")
}
运行结果:
    Scala:Spark
    Flink:Hadoop
代码4:
import scala.io.Source

object  Context_Helper{
    implicit class FileInhancer(file : File){
        def read = Source.fromFile(file.getPath).mkString
    }
    
    implicit class Op(x : Int){
        def addSAP(second : Int) = x + second
    }
}

object Implicits_Class{
    def main(args : Array[String]){
        import Context_Helper._
        println(a.addSAP(2))
        println(new File(path).read)
    }
}
# ## 最佳实践:Scala中的隐式转换通常都是写在伴生对象中

二、并发编程

Scala中使用Actor实现并发编程

Java的并发是使用共享全局变量的加锁机制

代码5import scala.actors.Actor

class HiActor extends Actor{
    def act(){
        while(true){
            receice{
                case name : String => println(name)
            }
        }
    }
}

val actor = new HiActor
#启动线程
actor.start()

#接收和发送消息
actor  ! "Spark"
运行结果:Spark
代码6import scala.actors.Actor
case class Basic(name : String, age : Int)
case class Worker(name : String, age : Int)

class BasicActor extends Actor{
    def act(){
        while(True){
            receive{
                case Basic(name, age) => print(name + ":" + age)
                case Worker(name, age) => print(name + ":" + age)
            }
        }
    }
}

val b = new BasicActor
b.start

b ! Basic("Scala", 13)
b ! Worker("Spark",7)
运行结果:
    Scala:13
    Spark:7
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值