Can someone explain me implicit conversions in Scala?

前端 未结 3 1767
长发绾君心
长发绾君心 2020-12-09 20:10

And more specifically how does the BigInt works for convert int to BigInt?

In the source code it reads:

...
implicit def int2bigInt(i: Int): BigInt =         


        
3条回答
  •  情深已故
    2020-12-09 20:33

    Complementing @GClaramunt's answer.

    Because it's way simpler to understand and grasp this concept by seeing a full example:

    // define a class
    case class Person(firstName: String, lastName: String)
    
    // must import this to enable implicit conversions
    import scala.language.implicitConversions
    
    // define the implicit conversion. String to Person in this case
    implicit def stringToPerson(name:String) = {
      val fields = name.split(" ");
      Person(fields(0), fields(1))
    }
    
    // method using the implicit conversion  
    def getPerson(fullName:String): Person = fullName
    
    val fooBar = getPerson("foo bar")
    println(fooBar.getClass())  // class Person
    println(fooBar.firstName)  // foo
    println(fooBar.lastName)  // bar
    

    I hope this example clarifies why and how one would want to use implicit conversions (not that I think converting String to Person makes a lot of sense but it's worth the illustration).

提交回复
热议问题