标签:bit main 声明 ring error: 嵌套使用 code require import
scala> def person(implicit name : String) = name //name为隐式参数
person: (implicit name: String)String
scala> person
<console>:9: error: could not find implicit value for parameter name: String
person
^
scala> implicit val p = "mobin" //p被称为隐式值
p: String = mobin
scala> person
res1: String = mobin
scala> implicit val p1 = "mobin1"
p1: String = mobin1
scala> person
<console>:11: error: ambiguous implicit values:
both value p of type => String
and value p1 of type => String
match expected type String
person
^
scala> def foo(msg : String) = println(msg)
foo: (msg: String)Unit
scala> foo(10)
<console>:11: error: type mismatch;
found : Int(10)
required: String
foo(10)
^
scala> implicit def intToString(x : Int) = x.toString
intToString: (x: Int)String
scala> foo(10)
10
class SwingType{
def wantLearned(sw : String) = println("兔子已经学会了"+sw)
}
object swimming{
implicit def learningType(s : AminalType) = new SwingType
}
class AminalType
object AminalType extends App{
import com.mobin.scala.Scalaimplicit.swimming._
val rabbit = new AminalType
rabbit.wantLearned("breaststroke") //蛙泳
}
class SwingType{
def wantLearned(sw : String) = println("兔子已经学会了"+sw)
}
package swimmingPage{
object swimming{
implicit def learningType(s : AminalType) = new SwingType //将转换函数定义在包中
}
}
class AminalType
object AminalType extends App{
import com.mobin.scala.Scalaimplicit.swimmingPage.swimming._ //使用时显示的导入
val rabbit = new AminalType
rabbit.wantLearned("breaststroke") //蛙泳
}
object Stringutils {
implicit class StringImprovement(val s : String){ //隐式类
def increment = s.map(x => (x +1).toChar)
}
}
object Main extends App{
import com.mobin.scala.implicitPackage.Stringutils._
println("mobin".increment)
}
隐式转换的时机:
1.当方法中的参数的类型与目标类型不一致时
标签:bit main 声明 ring error: 嵌套使用 code require import
原文地址:http://www.cnblogs.com/harvey888/p/6387702.html