Scala笔记(3)

隐式转换

需求:为一个已存在的类添加一个新的方法(类是第三方,并且你是拿不到源码的)

object ImplicitApp extends App {

implicit def man2Super(man: Man): Superman = new Superman(man.name)
val man = new Man(“tracy”)
man.canFly()

}

class Man(val name:String){
def eat(name:String): Unit ={

println(s"Man $name is eating...")

}
}

class Superman(val name:String){
def canFly(): Unit ={

println(s"Superman $name is flying...")

}
}
步骤:直接implicit关键字 加上def 定义一个隐式转换的方法,把要转换的当参数穿进去,返回值为转换后的对象
案例2:为java.io里添加一个read方法
//先定义RichFile class确定要转换后的效果,然后定义implicit进行转换过程
implicit def file2RichFile(file: File): RichFile = new RichFile(file)
val file = new File(“C:\Users\TracyChen\Desktop\Higher.txt”)
file.read()

class RichFile(val file:File){
def read(): Unit = {

println(scala.io.Source.fromFile(file).mkString)

}
}

操作外部数据
(文件)

val file=Source.fromFile("C:\\Users\\TracyChen\\Desktop\\Higher.txt")
//读取一整行
def readLine()={
  for (line <- file.getLines()){
    println(line)
  }
}
//读取字节
def readChar(): Unit = {
  for(ele <- file){
    println(ele)
  }
}

(MySQL)
val url = “”
val username = “”
val password = “”

classOf[driver address]
var connection: Connection = null
try {

connection = DriverManager.getConnection(url)
val statement  = connection.createStatement()
val resultSet = statement.executeQuery("")
while (resultSet.next()){
  val host = resultSet.getString("host")
  val user = resultSet.getString("user")
  println(s" $host : $user")
}

}catch {

case e:Exception => e.printStackTrace()

}finally {

if (connection == null) {
  connection.close()
}

}

正常来说生产上面都是要有数据库连接池的,需要创建connection都是去连接池取,然后close的时候直接放回连接池就可以

(XML)
val xml =XML.load(this.getClass.getClassLoader.getResource(“test.xml”))
println(xml)
如果要看xml里header标签下的东西,就用 val headerxml = xml “header”
如果要看xml里全局所有field的内容, 就用 val allFields = xml \ “fields”

                              for( field: fields)
                                  println(field)
                                  

看header标签下,name属性里的内容, 两种方法:

1. xml1 = (xml \ "header").**map(_ \ @name)**
2. xml2= (xml \ "header" \\ "@name" )

看header标签下,name属性里是不是有一个叫name = “tracy” 的内容:

val filter = (xml \\ "header").
filter(_.attribute("name").exists(_.text.equals("tracy"))

看header标签下,filed标签下的内容:
(xml \ “header” \ “filed”)
.map(x => (x “@name”, x.text, x “@required”))
.foreach(println)

    原文作者:SkinnyTracy
    原文地址: https://segmentfault.com/a/1190000020054341
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞