title: Kotlin by Lazy in Custom Views
body: <p>Currently, using <code>by Lazy</code> in a custom view break its visualisation in Android Studio. Using <code>isEditMode</code> can't be used because it is only available inside a method and not at variable initialisation scope. only workaround is using lateinit and or Delegates.notNull().</p>
  
  <p>Is there any workaround for this?</p>
  
  <p>Example:</p>
  
  <pre><code>class ImageViewCircleBg : ImageView {
  
      private var circleBgColor = R.color.colorPrimary
      private val paint by lazy {
          Paint().apply {
              style = Paint.Style.FILL
              isAntiAlias = true
          }
      }
  
      constructor(context: Context) : this(context, null)
      constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
      constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
  
          val ta = context.theme.obtainStyledAttributes(attrs, R.styleable.ImageViewCircleBg, 0, 0)
          circleBgColor = ta.getColor(R.styleable.ImageViewCircleBg_roundBgColor, circleBgColor)
          ta.recycle()
  
          this.paint.color = circleBgColor
      }
  </code></pre>
  
  <p>Produces the following error in android studio design window:</p>
  
  <pre><code>The following classes could not be instantiated:
  - ....ImageViewCircleBg (Open Class, Show Exception, Clear Cache)
   Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE  Exception Details java.lang.IncompatibleClassChangeError: Found class kotlin.Lazy, but interface was expected   at ...ImageViewCircleBg.getPaint(ImageViewCircleBg.kt:-1)
  </code></pre>
  
  <p>Replacing by lazy with this:</p>
  
  <pre><code>private val paint: Paint
  
      init {
          paint = Paint().apply {
              style = Paint.Style.FILL
              isAntiAlias = true
          }
      }
  </code></pre>
  
  <p>Solves the problem.</p>
  
  <p>Error:</p>
  
  <pre><code>java.lang.IncompatibleClassChangeError: Found class kotlin.lazy, but interface was expected
  </code></pre>