Scala: get default values ​​without creating an object

Suppose there is a class in the constructor with default values:

class Adapter(url: String = "127.0.0.1", port: Int = 8080)

Is it possible to get default values ​​for these parameters at runtime without instantiating this object?

Please do not ask about a precedent, it is more a question about the language itself.

+4
source share
2 answers

I assume that you are most interested in how default methods are implemented internally. Here is the javap parsing of your code (using a very useful :javap <classname>scala console command :

scala> class Adapter(url: String = "127.0.0.1", port: Int = 8080)
defined class Adapter

scala> :javap -c Adapter$ // Adapter$ because we want the companion object
Compiled from "<console>"
public class Adapter$ {

  ... 

  public java.lang.String $lessinit$greater$default$1();
    Code:
       0: ldc           #16                 // String 127.0.0.1
       2: areturn       

  public int $lessinit$greater$default$2();
    Code:
       0: sipush        8080
       3: ireturn       

  ...

, , , -. :

scala> Adapter.getClass.getMethod("$lessinit$greater$default$1").invoke(Adapter) 
res8: Object = 127.0.0.1

scala> Adapter.getClass.getMethod("$lessinit$greater$default$2").invoke(Adapter) 
res9: Object = 8080

, , .. . @Sparko .

: methodName + "$default$" + parameterNumber. , , , "<init> ". , , , "$ lessinit $" "$ lessinit $ $default $0" .

+6

-?

case class Adapter(url: String = Adapter.defaultURL, port: Int = Adapter.defaultPort)

object Adapter {
    val defaultURL = "127.0.0.1"
    val defaultPort = 8080
}

private, case class

+2

Source: https://habr.com/ru/post/1619067/


All Articles